先來看這個例子,請問下面表達式的值是多少。
0 == null
如果你不確定答案,或者想知道語言內部怎麼處理,就可以去查看規格,7.2.12小節是對相等運算符(==)的描述。
規格對每一種語法行爲的描述,都分成兩部分:先是總體的行爲描述,然後是實現的算法細節。相等運算符的總體描述,只有一句話。
"The comparison x == y, where x and y are values, produces true or false."
上面這句話的意思是,相等運算符用於比較兩個值,返回true或false。
下面是算法細節。
1. ReturnIfAbrupt(x).
2. ReturnIfAbrupt(y).
3. If Type(x) is the same as Type(y), then
Return the result of performing Strict Equality Comparison x === y.
4. If x is null and y is undefined, return true.
5. If x is undefined and y is null, return true.
6. If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y).
7. If Type(x) is String and Type(y) is Number,
return the result of the comparison ToNumber(x) == y.
8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
return the result of the comparison x == ToPrimitive(y).
11.If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
return the result of the comparison ToPrimitive(x) == y.
12. Return false.
上面這段算法,一共有12步,翻譯如下。
1.如果x不是正常值(比如拋出一個錯誤),中斷執行。
2.如果y不是正常值,中斷執行。
3.如果Type(x)與Type(y)相同,執行嚴格相等運算x === y。
4.如果x是null,y是undefined,返回true。
5.如果x是undefined,y是null,返回true。
6.如果Type(x)是數值,Type(y)是字符串,返回x == ToNumber(y)的結果。
7.如果Type(x)是字符串,Type(y)是數值,返回ToNumber(x) == y的結果。
8.如果Type(x)是布爾值,返回ToNumber(x) == y的結果。
9.如果Type(y)是布爾值,返回x == ToNumber(y)的結果。
10.如果Type(x)是字符串或數值或Symbol值,Type(y)是對象,返回x == ToPrimitive(y)的結果。
11.如果Type(x)是對象,Type(y)是字符串或數值或Symbol值,返回ToPrimitive(x) == y的結果。
12.返回false。
由於0的類型是數值,null的類型是Null(這是規格4.3.13小節的規定,是內部Type運算的結果,跟typeof運算符無關)。因此上面的前11步都得不到結果,要到第12步才能得到false。
0 == null // false
原文出處:阮一峯博客http://www.ruanyifeng.com/blog/2015/11/ecmascript-specification.html