【js】0 == null 和 0 == undefined 转换结果为什么false

本文探讨了在JavaScript中0==null返回false的原因。通过详细解释ECMAScript的相等运算符算法步骤,揭示了这一现象背后的逻辑机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记得0转换为布尔类型的值是false,众所周知null == undefined是为true,本以为 0 == null0 == 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 入门

ecma-international 规范

知乎 | JavaScript中 0==null为何是false?

CSDN | 为什么 0 == null 等于 false?

特此记录一下探索路程也为了加深此印象,如果你也看到该文,希望能对你有帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值