为什么(null == false)和(null == true)都返回false? [英] Why (null == false) and (null == true) both return false?

查看:243
本文介绍了为什么(null == false)和(null == true)都返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 null 是一个没有属性或功能的对象。



然而,我很困惑为什么 console.log(null == false); console.log(null == true); 两者都返回false。



null boolean

解决方案

这是因为抽象等式比较算法要求如果 Type(x) 类型(y) 是一个布尔值表达式 x == y 然后应通过将布尔值强制转换为数字 ToNumber ,将 true 转换为1, false +0



这意味着的所有比较都是真的==某事某事== true 结果 1 ==某事某事== 1 (替换 true 1 false +0 对于 false )。



Null类型不等于1或+ 0(事实上,null只能与AECA中的 undefined 相比)。 / p>

MDN 如果你想了解更多信息,那么值得一看。



然而,如果你强迫 null 到一个数字是强迫 +0 所以 + null == false 实际上返回 true


I know that null is an object with no attributes or functions.

However, I am confused that why console.log(null == false); and console.log(null == true); both return false.

What are the conversion rules between null and boolean?

解决方案

This is because the Abstract Equality Comparison Algorithm requires that if Type(x) or Type(y) is a Boolean in the expression x == y then the Boolean value should be coerced to a number via ToNumber, which converts true to 1 and false to +0.

This means that any comparison of true == something or something == true results in 1 == something or something == 1 (replacing true and 1 with false and +0 for false).

The Null type does not compare as equal to either 1 or +0 (in fact, null is only comparable to undefined in the AECA).

There is a detailed discussion of all of the different kinds of equality in JavaScript on MDN that is well worth looking at if you want to know more.

However, if you coerce null to a number it is coerced to +0 so +null == false actually returns true.

这篇关于为什么(null == false)和(null == true)都返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆