为什么检查三个字符串之间的相等性不起作用,但检查三个数字之间的相等性呢?

why checking equality between three strings not works but between three numbers does?

我已经检查了 javascript 中三个数字之间的相等性并且有效。喜欢:

1 == 1 == 1 //true
2 == 3 == 4 //false
2 == 3 == 3 //false

但是当我尝试在三个字符串之间进行此检查时,它不起作用:

'some string' == 'some string' == 'some string' //false
'a' == 'a' == 'a' //false

有人知道为什么会这样吗?
提前致谢。

因为

'some string' == 'some string' == 'some string'

按从左到右的顺序计算 == 运算符。相当于

('some string' == 'some string') == 'some string'

也就是

true == 'some string'

这是错误的,因为根据 spec:

将布尔值与其他值进行比较时
  1. If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.

当右边是字符串时,解析为

1 == 'some string'

然后运行

  1. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).

但是 ToNumber('some string')NaN

console.log(Number('some string'));

所以比较结果为 false

另一方面,对于 1 == 1 == 1,遵循相同的过程:

1 == 1 == 1
(1 == 1) == 1
true == 1
// Rule 8, turn left side into a number:
1 == 1
true

结论:始终使用===。如果你使用==,你会遇到奇怪的行为。

1 == 1 == 1 可以解释为 (1 == 1 (true) == 1) 为真。 但是 'a' == 'a' == 'a' 将被解释为 ('a' == 'a' (true) == 'a') 这将是假的。因为 true 不等于 'a'.