×

# 说说为什么 [] == ![] 为true

• 首先看看==这个操作内部是如何工作的

The production EqualityExpression: EqualityExpression == RelationalExpression is evaluated as follows:

1. Let lref be the result of evaluating EqualityExpression
2. Let lval be GetValue(lref)
3. Let rref be the result of evaluating RelationalExpression
4. Let rval be GetValue(rref)
5. Return the result of performing abstract equality comparison rval==lval
• 根据上面的步骤，我们来对问题作如下解析：
1. 先求GetValue([])
2. 再求GetValue(![])
3. 最后求 GetValue([]) == GetValue(![])

1. If Type(V) is not Reference, return V
2. ....

1. GetValue([])为 []
2. GetValue(![])为 false， （这里！会使得[]强制转化为Boolean类型）
3. 这里就成了求 [] == 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:

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

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

1. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

• 查看ToPrimitive的工作机制（9.1）

Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object,
passing the optional hint PreferredType. The behaviour of the
[[DefaultValue]] internal method is defined by this specification for all native
ECMAScript objects in 8.12.8.

When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:

1. Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
2. If IsCallable(valueOf) is true then
a. Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
b. If val is a primitive value, return val.
3. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
b. If str is a primitive value, return str.
...

"" == 0

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

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