在 javascript 中使用 != null 和 != undefined 在功能上有什么区别吗?

Is there any function difference between using != null and != undefined in javascript?

在javascript中,使用!= null!= undefined在功能上有什么区别吗?

是否有可以分配给 myVar 的值,这将导致这两行代码计算出不同的结果?

console.log(myVar != undefined)
console.log(myVar != null)

如果您了解这两个操作的性能,我也很想知道。

==!= 运算符使 "type conversion" 仅比较值本身。那么不,在这种情况下使用 "undefinied" 或 "null" 没有区别,都代表 "empty".

但是,如果您改用 ===!==,它会检查类型和值,而不会进行任何类型转换。两条线的结果会不同。

myVar = null;
console.log(myVar !== undefined) //true
console.log(myVar !== null) //false

没有功能差异。当 xnullundefined 时,x != undefinedx != null 都仅计算为 false。对于 x.

的所有其他值,它们都评估为真

也没有性能差异。

不要混淆 undefined and null,因为它们不是一回事。

空:

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values.

未定义:

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.


如果变量包含的值既不是 null 也不是 undefined,那么您的情况没有区别。

const value = 3;

console.log(value !== undefined) //true
console.log(value !== null) //true

但是,测试变量是 null 还是 undefined 的更好方法是使用 ! 否定作为值 nullundefined将被解析为真。

const undefinedValue = undefined;
const nullValue = null;

console.log(!undefinedValue);
console.log(!nullValue);

这里有一些例子。

var someVariable = undefined;

console.log(someVariable !== undefined, "; undefined !== undefined");
console.log(someVariable !== null, "; undefined !== null");

var someVariable = null;

console.log(someVariable !== undefined, "; null !== undefined");
console.log(someVariable !== null, "; null !== null");


var someVariable = undefined;
console.log(!someVariable);

var someVariable = null;
console.log(!someVariable);

没有区别 正如你在下面看到的 table 用于 JS == 测试(关注 null/undefined row/column)(来源:here)。所以 myVar!=null 仅当 myVar 值不是 null 而不是 undefined 时才为真(与 myVar != undefined 相同)

看起来两者具有相似的性能(我在 Mac OS X 10.13.4 HighSierra: Chrome 71.0.3578、Firefox 65.0.0 和 Safari 11.1 上进行了测试。 0 - 您可以 运行 在浏览器中测试 here)

let myVar1=null;
let myVar2=undefined;