javascript - Javascript 中 null 和 undefined 与 bool 值的比较

标签 javascript ecmascript-6 equality ecmascript-5 ecma

根据ES5 section 11.9.3它说的是

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).

当我尝试比较

let a = null, b = null;

a == false; // false
b == false; // false
a == "";    // false
b == "";    // false
a == 0;     // false
b == 0;     // false

我在这里期待的a == false返回 false 是 false被强制为数字 0所以比较将变成 a == 0然后进行下一个强制转换,其类型为 null == 0 , null 应该被强制为 Number这是 0 。所以最后它应该返回 true 0 == 0 .

我从 ES5 11.9.3 得到的是

If x is null and y is undefined, return true.
If x is undefined and y is null, return true.

提到了 null 和 undefined。

ES 11.9.3 部分的第 10 点表示,如果您的比较不符合以上 9 个标准 return false .

我的比较是否返回 false根据 ES5 11.9.3 中的第 10 点,还是我在这里遗漏了一些东西>

最佳答案

从根本上说,是的,当将 nullnull 以外的任何内容进行比较时,您得到的是 false ,这是正确的未定义,因为您到达了算法的最后一步,即return false

如果您问为什么 null == falsefalse,简短的回答是:因为 null 只是 = = null未定义

长答案在您指出的抽象相等操作中,这是最新版本:https://tc39.es/ecma262/#sec-abstract-equality-comparison步骤 1-8 不适用,但步骤 9 适用:

  1. If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).

(ToNumber之前的!没有否定,它是关于突然完成的规范注释。这有时会让人感到困惑。)

现在我们有了null == 0。步骤 1-12 均不适用,因此步骤 13 中的 return false 适用。

(我应该注意,当 xnull 时,步骤 11 中的“If Type(x) is Object”不为 true,即使 typeof null"object"Type operationtypeof 不同,Type(null) 是 Null。)

您在评论中说过:

I was just curious about null comparisons, so I mentioned all null comparisons in question.

是的,你说得对,你最终到达了终点。该算法中与 null 相关的唯一部分是步骤 2 和 3,检查一个操作数是否为 null 而另一个操作数是否为 undefined 以及如果是,则返回true

关于javascript - Javascript 中 null 和 undefined 与 bool 值的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58679199/

相关文章:

javascript - 误报 "Lexical declarations require ECMAScript 6"和 "TypeScript 1.x feature. Current language is 1.4"错误消息

带有@字符的Javascript ES6导入

c++ - 使用 '='运算符在C++中使两个数组相等

javascript - WebRTC冰状态= "failed"黑色视频

javascript - 如何在 View 模型不是函数的情况下创建 KnockoutJS 计算可观察对象?

javascript - 使用 Vue.js 过渡来显示内容,但只让过渡发生一次

javascript - 取消 Angular 服务 promise

javascript - 为什么卡片在 Javascript ES6 "Game of War"中丢失?

java - 当两个对象相同时,为什么 equals() 方法返回 false?

java - 不需要将代码片段转换为另一种语言 = op?