如下所示,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
当前回答
这是按规格的。
12.5 The if Statement ..... 2. If ToBoolean(GetValue(exprRef)) is true, then a. Return the result of evaluating the first Statement. 3. Else, ....
根据规范,ToBoolean是
抽象操作ToBoolean根据表11将其参数转换为Boolean类型的值:
这个表格是这样描述字符串的:
如果参数为空String(其长度为零),则结果为假; 否则结果为真
现在,为了解释为什么"0" == false,您应该读取相等运算符,它表示它从抽象操作GetValue(lref)中获得其值,与右侧的相同。
将相关部分描述为:
if IsPropertyReference(V), then a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get be the special [[Get]] internal method defined below. b. Return the result of calling the get internal method using base as its this value, and passing GetReferencedName(V) for the argument
或者换句话说,字符串有一个基元,它会回调内部的get方法,结果看起来是false。
如果你想用GetValue运算来求值,请使用==,如果你想用ToBoolean运算,请使用===(也称为“严格”相等运算符)
其他回答
显示问题的表格:
和= =
这个故事的寓意使用===
表生成credit: https://github.com/dorey/JavaScript-Equality-Table
// 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.
0周围的引号使它成为一个字符串,它的值为true。
删除引号,它应该工作。
if (0) console.log("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)
这就是为什么你应该尽可能使用严格相等===或严格相等!== =的原因
"100" == 100
为True,因为这只检查值,而不是数据类型
"100" === 100
检查值和数据类型