如下所示,Javascript中的"0"为false:

>>> "0" == false
true

>>> false == "0"
true

那么下面为什么打印“哈”呢?

>>> if ("0") console.log("ha")
ha

当前回答

原因是,当显式执行"0" == false时,两边都被转换为数字,然后执行比较。

如果执行:if ("0") console.log("ha"),则正在测试字符串值。任何非空字符串为真,而空字符串为假。

Equal (==) If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory. (From Comparison Operators in Mozilla Developer Network)

其他回答

我从搜索中心来到这里,寻找将“0”计算为布尔值的解决方案。 上面已经解释了技术细节,所以我不会深入讨论它,但我发现一个快速的类型转换解决了它。

因此,如果有人像我一样,想要像PHP一样,将字符串1或0计算为布尔值。然后你可以做上面的一些事情,或者你可以像这样使用parseInt():

x = "0";
if(parseInt(x))
//false

这都是因为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

这就是为什么你应该尽可能使用严格相等===或严格相等!== =的原因

"100" == 100

为True,因为这只检查值,而不是数据类型

"100" === 100

检查值和数据类型

显示问题的表格:

和= =

这个故事的寓意使用===

表生成credit: https://github.com/dorey/JavaScript-Equality-Table

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/