检查未定义和null的不等式(!==)和检查未定义和null的柯夫不等式(!=)之间有区别吗?

Is there a difference between checking for inequality (!==) against undefined and null and just checking for corcive inequality (!=) against null?

本文关键字:检查 不等式 null 未定义 有区别 之间      更新时间:2023-09-26

如果我将变量传递给Coffescript中的存在运算符,它将被转换为一对!==比较:

            compiles to
Coffeescript ------> JS
a?                   typeof a !== "undefined" && a !== null;

但是如果我使用文字或表达式,它会使用!=比较:

            compiles to
Coffeescript ------> JS
17?                  17 != null;
//same thing for regexps, strings, function calls and other expressions
//as far as I know.

有什么理由更喜欢双!== s而不是较短的!= null,除了可能使JSLint高兴吗?

简短的回答:它们在行为上是等同的,!= null编译是一种优化。无论如何,x?意味着x既不是null也不是undefined

人们在CoffeeScript问题跟踪器上问了很多。x != null没有作为x?的编译输出到处使用的原因是,如果x不存在,x != null(或与x的任何其他比较)会导致运行时错误。在Node REPL上试试:

> x != null
ReferenceError: x is not defined

"不存在",我的意思是没有var x,没有window.x = ...,并且你不在一个x是参数名称的函数中。(CoffeeScript编译器无法识别window.x情况,因为它没有对您所处的环境做出任何假设。)因此,除非在当前作用域中有var x声明或名为x的参数,否则编译器必须使用typeof x !== "undefined"来防止进程可能崩溃。

我可以理解为什么人们对此感到困惑。ECMAScript:

a?

等价于:

typeof a !== 'undefined' && a !== undefined && a !== null && a !== 0 && a !== false && a !== '';

Coffeescript重构为:

typeof a !== "undefined" && a !== null;

意味着:

var a = false;
a?;  // evaluates to true?

正确吗?