如下所示,Javascript中的"0"为false:
>>> "0" == false
true
>>> false == "0"
true
那么下面为什么打印“哈”呢?
>>> if ("0") console.log("ha")
ha
如下所示,Javascript中的"0"为false:
>>> "0" == false
true
>>> false == "0"
true
那么下面为什么打印“哈”呢?
>>> if ("0") console.log("ha")
ha
当前回答
The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).
其他回答
if (x)
使用JavaScript内部的toBoolean (http://es5.github.com/#x9.2)强制x
x == false
使用内部tonnumber强制(http://es5.github.com/#x9.3)或对象的toPrimitive强制(http://es5.github.com/#x9.1)
详情见http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
显示问题的表格:
和= =
这个故事的寓意使用===
表生成credit: https://github.com/dorey/JavaScript-Equality-Table
==相等运算符在将参数转换为数字后求值。 因此字符串0" 0"被转换为数字数据类型,布尔值false被转换为数字0。 所以
"0" == false // true
同样适用于'
False == "0" //true
===严格的相等性检查使用原始数据类型计算参数
"0" === false // false,因为"0"是字符串,false是布尔值
同样适用于
False === "0" // False
In
if(“0”) console.log(“ha”);
String "0"不与任何参数进行比较,并且String在与任何参数进行比较之前都是真值。 就像
if (true) console.log (" ha ");
But
If (0) console.log("ha");//空控制台行,因为0是假的
`
0周围的引号使它成为一个字符串,它的值为true。
删除引号,它应该工作。
if (0) console.log("ha")
这都是因为ECMA规格…"0" == false,因为这里指定的规则http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.3…if('0')的结果为true,因为这里指定的规则http://ecma262-5.com/ELS5_HTML.htm#Section_12.5