我以为我知道 ==
的怪癖以及 JavaScript 中所有奇怪的类型转换,但今天我偶然发现了一件没有任何意义的事情 对我来说:
'\t' == false
// => true
这是为什么?
显然,'\t'
不是假值,如果与 ||
结合使用,它会像预期的那样工作:
'\t' || 42
// => '\t'
另一方面,toString
也不会在 false
上调用,请参阅:
'\t' == 'false'
// => false
这让我想到选项卡可能会转换为 bool 值,但是:
Boolean('\t') == false
// => false
那么,问题是:这是为什么?
参见 Abstract Equality Comparison: :
The comparison x == y
, where x and y are values, produces true or false. Such a comparison is performed as follows:
因此,在您的情况下,x
是一个字符串,y
是一个 bool 值。这里满足的第一个条件是:
- If Type(y) is Boolean, return the result of the comparison
x == ToNumber(y)
.
把支票变成
'\t' == 0
然后满足:
- If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
和 ToNumber('\t') === 0
:
console.log(Number('\t'));
把支票变成
0 == 0
与
相同
0 === 0
或为真
。
请注意,虽然由所有空格组成的字符串是 == false
,但在这样的字符串上调用 Boolean 将返回 true
,因为该字符串的长度不为零:
console.log(
Boolean(' '),
Boolean('\t')
);
当然,最好始终避免 ==
- 使用 ===
代替,这样您就不必担心这些愚蠢的强制转换规则。