如下所示,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
当前回答
0周围的引号使它成为一个字符串,它的值为true。
删除引号,它应该工作。
if (0) console.log("ha")
其他回答
显示问题的表格:
和= =
这个故事的寓意使用===
表生成credit: https://github.com/dorey/JavaScript-Equality-Table
这是因为JavaScript在布尔上下文和代码中使用类型强制
if ("0")
将在布尔上下文中被强制为true。
在Javascript中还有其他的真值,在布尔上下文中会被强制为真,因此执行if块:-
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)
原因是,当显式执行"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)
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/
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).