IE 检测:这到底是什么意思?

IE detection: what the heck does this mean?

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

if (false || !!document.documentMode)

而且我不了解这个装置。为什么需要与 false 进行 OR 并使用 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>

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

因为 document 总是定义的,并且它的 属性 documentMode 的存在是真实的,所以这些是完全同义的:

if (false || !!document.documentMode)

和:

if(document.documentMode)

(如果 document 可能是 undefined,那么第一个代码将完全失败。)

Why is it necessary to OR with false [...]

没有必要。 || operator, given false for the 1st operand, will 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'

[...] and use NOT twice?

这部分already has an answer here on SO.

两个! operators together perform a "ToBoolean" type conversion, as a slighter shorter version of using 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)