Javascript 相等运算符

Javascript equality operators

在 David Flanagan 的 Javascript 指南中,有一句话:

the == operator never attempts to convert its operands to boolean

所以我在这里做了一个小测试:

var a = false;
var b = ""; // empty string
a == b; //returns true

Abstract Equality Comparison Algorithm有一点:

e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.

如果 y 是字符串数据类型(无需转换),x 和 y 如何同时为真?

幕后发生的事情是

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

Number(false) == ""

接着是

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

Number(false) == Number("") -> 0 == 0

How can x and y be both true if y is string data type (without conversion)?

它们并不都是 true,但在类型转换后它们的值是相等的。

the == operator never attempts to convert its operands to boolean

这是正确的,如果您检查比较算法,您会发现类型永远不会隐式转换为 Boolean

参考文献: