记得0转换为布尔类型的值是false,众所周知null == undefined是为true,本以为
0 == null
和0 == undefined
也为true,但答案结果却为false
。
0单独在if语句是会转换为false的
if(0){
console.log('0在if语句转换true');
}else{
console.log('0在if语句转换为false');
}
打印结果如下:
百思不得其解故查询了一下,得到了网上的答案:
相等运算符用于比较两个值,返回true或false。
下面是算法细节。
“The comparison x == y, where x and y are values, produces true or false.”
ReturnIfAbrupt(x).
ReturnIfAbrupt(y).
If Type(x) is the same as Type(y), then Return the result of
performing Strict Equality Comparison x === y.If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
If Type(x) is Number and Type(y) is String, return the result of the
comparison x == ToNumber(y).If Type(x) is String and Type(y) is Number, return the result of the
comparison ToNumber(x) == y.If Type(x) is Boolean, return the result of the comparison ToNumber(x)
== y.If Type(y) is Boolean, return the result of the comparison x ==
ToNumber(y).If Type(x) is either String, Number, or Symbol and Type(y) is Object,
then return the result of the comparison x == ToPrimitive(y).If Type(x) is Object and Type(y) is either String, Number, or Symbol,
then return the result of the comparison ToPrimitive(x) == y.Return false.
上面这段算法,一共有 12 步,翻译如下。
如果x不是正常值(比如抛出一个错误),中断执行。
如果y不是正常值,中断执行。
如果Type(x)与Type(y)相同,执行严格相等运算x === y。
如果x是null,y是undefined,返回true。
如果x是undefined,y是null,返回true。
如果Type(x)是数值,Type(y)是字符串,返回x == ToNumber(y)的结果。
如果Type(x)是字符串,Type(y)是数值,返回ToNumber(x) == y的结果。
如果Type(x)是布尔值,返回ToNumber(x) == y的结果。
如果Type(y)是布尔值,返回x == ToNumber(y)的结果。
如果Type(x)是字符串或数值或Symbol值,Type(y)是对象,返回x == ToPrimitive(y)的结果。
如果Type(x)是对象,Type(y)是字符串或数值或Symbol值,返回ToPrimitive(x) == y的结果。
返回false。
由于0的类型是数值,null的类型是 Null(这是规格4.3.13 小节的规定,是内部 Type 运算的结果,跟typeof运算符无关)。因此上面的前 11 步都得不到结果,要到第 12 步才能得到false。
0 == null // false
参考:
ECMAScript 6 入门
知乎 | JavaScript中 0==null为何是false?
CSDN | 为什么 0 == null 等于 false?
特此记录一下探索路程也为了加深此印象,如果你也看到该文,希望能对你有帮助。