抽象相等()
抽象等式運算子的運算元在轉換為公共型別後進行比較。如何進行此轉換是基於運算子的規範:
7.2.13 抽象相等比較
比較
x == y,其中x和y是值,產生true或false。這樣的比較如下進行:
- 如果
Type(x)與Type(y)相同,那麼:
- **一個。**返回執行 Strict Equality Comparison
x === y的結果。
- 如果
x是null而y是undefined,則返回true。- 如果
x是undefined而y是null,那麼返回true。- 如果
Type(x)是Number而Type(y)是String,則返回比較結果x == ToNumber(y)。- 如果
Type(x)是String而Type(y)是Number,則返回比較結果ToNumber(x) == y。- 如果
Type(x)是Boolean,則返回比較結果ToNumber(x) == y。- 如果
Type(y)是Boolean,則返回comparison x == ToNumber(y)的結果。- 如果
Type(x)是String,Number,或Symbol,Type(y)是Object,則返回比較結果x == ToPrimitive(y)。- 如果
Type(x)是 Object 而Type(y)是String,Number或Symbol,則返回比較結果ToPrimitive(x) == y。- 返回
false。
例子:
1 == 1; // true
1 == true; // true (operand converted to number: true => 1)
1 == '1'; // true (operand converted to number: '1' => 1 )
1 == '1.00'; // true
1 == '1.00000000001'; // false
1 == '1.00000000000000001'; // true (true due to precision loss)
null == undefined; // true (spec #2)
1 == 2; // false
0 == false; // true
0 == undefined; // false
0 == ""; // true