"0"
是包含字符0的字符串,它不是数值0
。计算结果的唯一字符串类型值false
是""
。
"0"
是真实的。
ECMAScript 262 规范的第 9.2 节定义了不同类型如何转换为布尔值:
Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN; otherwise the
result is true.
String The result is false if the argument is the empty String (its length is
zero); otherwise the result is true.
Object true
但是,只有在比较 using 时才严格遵循这一点===
。
使用时,Boolean('0')
您将值转换'0'
为布尔值(与使用相同!!'0'
)。当'0'
与 进行松散比较时false
,布尔值被转换为一个数字(定义在这里)。false
,当转换为数字时,变为0
。这意味着最终的计算'0' == 0
等于true
。
总结上面 ECMAScript 规范链接部分的相关部分:
- 让x =
'0'
和y = false
。
- 检查y的类型是否为布尔值。
- 如果为 true,则将y转换为数字。
- 将x与y的数字等价物进行比较。
在我们的例子中,它的 JavaScript 实现是:
var x = '0', // x = "0"
y = false; // y = false
if (typeof y === "boolean") {
y = +y; // y = 0
}
console.log( x == y ); // "0" == 0
-> true