如果简写语句在javascript中不起作用,为什么会扩展以下内容?

时间:2012-06-26 00:58:27

标签: javascript

这是我第一次尝试写速记,但是如果说扩展版本不能像我想象的那样工作,那会让我感到困惑。

代码1 - 无效

if(document.getElementById == true) {
        alert("The document object model is supported by: " + navigator.appName);   
    }

代码2 - 有效吗

if(document.getElementById != false) {
            alert("The document object model is supported by: " + navigator.appName);   
        }

代码3 - 有效的简写

 if(document.getElementById) {
            alert("The document object model is supported by: " + navigator.appName);   
        }

为什么如果我将3中的速记扩展到第一个代码示例不起作用,如果我将其等于!= false,为什么它会起作用?

5 个答案:

答案 0 :(得分:2)

您的第一个if声明:

if(document.getElementById == true) {

...不起作用,因为document.getElementById是一个函数,它是一种对象,并且一个对象不等于true

您的第二个if声明:

if(document.getElementById != false) {

...并没有真正起作用 - 即使你认为它确实有效 - 因为(我假设)你只是在浏览器中测试了它,在这种情况下定义了document.getElementById,同样,{ {1}}是一个函数,一种对象,不等于.getElementById但是,如果false 定义,那么如果.getElementById 也是 {if测试将有效地进行测试{1}}。所以测试没有按照你的想法进行。

您的第三个undefined != false声明:

true

......确实有效。它起作用的原因是因为JavaScript具有“truthy”和“falsy”表达式的概念。数字0,空字符串if if(document.getElementById) { ""undefined,当然还有null都是“虚假”值。几乎所有其他东西,包括非零数字,非空字符串和任何对象(包括函数)都是“真实的”。如果NaN语句中的表达式为“truthy”,则将执行if块。

(最后,确实没有必要测试false是否存在 - 如果您能找到运行JS但未定义该方法的浏览器,我会感到惊讶。)

答案 1 :(得分:1)

因为document.getElementById是一个现有的函数,但不是true。尝试document.write(document.getElementById)并查看结果。它不会true评估false

见行动here

您不必将其与布尔值进行比较,因此最好做的是:

if(document.getElementById){
    //Do something
}

答案 2 :(得分:1)

代码1是真实的,但不是真的。 getElementById是一个对象,但它不是一个布尔值,因此将它与一个进行比较将为false。

这是一个解释真实性和虚假性概念的博客:http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

答案 3 :(得分:1)

第一个不起作用,因为typeof document.getElementById是'function',它的值是本机代码,而不是布尔“true”。

重新。你的第三个例子,也试试这个:

if (!!document.getElementById) ...

!!将在结果上强制使用布尔类型。

答案 4 :(得分:0)

以下是ECMAScript规范的答案:

查看评估if statements的过程:在步骤3中,过程调用ToBoolean,将对象强制转换为值trueToBoolean函数是我们得到“truthy”和“falsy”值的概念;它们是由ToBoolean分别投放到truefalse的值。

现在查看用于==运算符的Abstract Equality Comparison OperationObject == boolean的程序流程比简单调用ToBoolean复杂得多。它是这样的:

For some comparison x == y...

1.  If Type(x) is different from Type(y), go to step 14.
19. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

(Go back to step 1, with the boolean cast to a Number by ToNumber[1], then...)

21. If Type(x) is Object and Type(y) is either String or Number, return
    the result of the comparison ToPrimitive(x)== y.

(ToPrimative[2] calls the object's toString method; now compare String == Number)

17. If Type(x) is String and Type(y) is Number, return the result of the
    comparison ToNumber(x)== y.

(ToNumber turns the string "function()..." into NaN. Finally...)

5. If x is NaN, return false

进一步参考:

[1] ToNumber

[2] ToPrimative调用[[DefaultValue]],这是一个很长的问题。幸运的是,在这种情况下,它会在第2步快速解决。