如下所示,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" == 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)
其他回答
在JS中,“==”符号不检查变量的类型。因此,“0”= 0 = false(在JS中为0 = false),在这种情况下将返回true,但如果使用“===”,结果将为false。
当你使用"if"时,在以下情况下它将是"false":
[0, false, '', null, undefined, NaN] // null = undefined, 0 = false
So
if("0") = if( ("0" !== 0) && ("0" !== false) && ("0" !== "") && ("0" !== null) && ("0" !== undefined) && ("0" !== NaN) )
= if(true && true && true && true && true && true)
= if(true)
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/
原因是,当显式执行"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)
// I usually do this:
x = "0" ;
if (!!+x) console.log('I am true');
else console.log('I am false');
// Essentially converting string to integer and then boolean.
在PHP中,字符串“0”是假的(false-when-used-in-boolean-context)。在JavaScript中,所有非空字符串都是真值。
技巧是==针对布尔值并不在布尔上下文中求值,它转换为数字,在字符串的情况下是通过解析为十进制来完成的。所以你得到0而不是truthiness boolean true。
这是一个非常糟糕的语言设计,这也是我们尽量不使用不幸的==操作符的原因之一。请使用===代替。