对于 == 这种,ecma有定义,感觉,记这些东西,纯属蛋疼。。
所以,面试碰到类似的,我直接溜走。。
7.2.14 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. 1. If Type(x) is the same as Type(y), then
a. a. Return the result of performing Strict Equality Comparison x === y.
2. 2. If x is null and y is undefined, return true.
3. 3. If x is undefined and y is null, return true.
4. 4. NOTE: This step is replaced in section B.3.7.2.
5. 5. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
6. 6. If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
7. 7. If Type(x) is BigInt and Type(y) is String, then
a. a. Let n be ! StringToBigInt(y).
b. b. If n is NaN, return false.
c. c. Return the result of the comparison x == n.
8. 8. If Type(x) is String and Type(y) is BigInt, return the result of the comparison y == x.
9. 9. If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
10. 10. If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
11. 11. If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return the result of the comparison x == ? ToPrimitive(y).
12. 12. If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return the result of the comparison ? ToPrimitive(x) == y.
13. 13. If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then
a. a. If x or y are any of NaN, +∞ , or -∞ , return false.
b. b. If (x) = (y), return true; otherwise return false.
14. 14. Return false.
https://262.ecma-international.org/12.0/
【 在 javaboy (喝了咖啡就话多-_-;) 的大作中提到: 】
: 最后那个 0 == false 的例子确实是js相关的,不是蠢问题。
: 在js标准里==操作符的算法基本就是查表,规则可以有逻辑性,也可以没有逻辑性。每一种情况都是当特例处理的。从你的描述看,估计你误以为0==false是把false隐式转换成了number再比较。实际上不是这样的。js标准看到左边是number右边是boolean,就去规则库里找到量相应的
: 换个说法:0==false之所以结果是true,并不是像c那样根据优先级cast然后根据语义算出来,纯粹是因为js发明人选择了true。
: ...................
--
FROM 220.181.41.*