IE检测:这是什么意思?

时间:2015-04-09 21:06:35

标签: javascript internet-explorer

我正在查看一段检测IE浏览器的代码:

if (false || !!document.documentMode)

我不理解这个装置。为什么有必要使用OR和false并使用NOT两次?

如果我只是在IE9,FF或Opera中加载下面的文件,那么IE会告诉我文档模式是存在的,而后两者会说不然:

<html>
<head>
    <script>function ld() {
        if (document.documentMode){
            document.getElementById("p1").innerHTML = 'Document Mode detected'
        }
        else {
            document.getElementById("p1").innerHTML = 'No Document Mode'
        }
    }</script>
</head>
<body onload="ld()">
<p id="p1"></p>
</body>
</html>

这还不够吗?为什么?目前尚不清楚,因为如果我用原始问题中的条件替换条件,结果将完全相同。我错过了什么?

2 个答案:

答案 0 :(得分:2)

  

为什么有必要与假[...]

进行OR

没有必要。 || operator,第一个操作数为falsewill always return the 2nd operand

// lval || rval (minus short-circuiting)
function OR(lval, rval) {
    if (lval)
        return lval;
    else
        return rval;
}

OR(false, 'foo') // 'foo'
  

[...]并且不使用两次?

这部分already has an answer here on SO

两个! operators一起执行&#34; ToBoolean&#34;类型转换,作为使用Boolean() without new的更简短的版本:

!!document.documentMode        // true/false
Boolean(document.documentMode) // true/false

此外,if will perform the same type conversion本身。

2. If ToBoolean(GetValue(exprRef)) is true

因此,在为真实性测试单个值时,!!也不一定如你所建议的那样:

if (document.documentMode)

答案 1 :(得分:1)

由于始终定义document,并且其属性documentMode的存在是真实的,因此这些完全是同义词:

if (false || !!document.documentMode)

if(document.documentMode)

(如果document可能未定义,则第一个代码将完全失败。)

相关问题