问题描述
在javascript中,使用!= null
和!= undefined
之间有什么功能区别吗?
是否有可以分配给myVar
的值,它会导致这两行代码计算出不同的结果?
console.log(myVar != undefined)
console.log(myVar != null)
如果您对这两个操作的性能有所了解,我也很想知道。
1楼
没有功能差异。
x != undefined
和x != null
都只在x
为null
或undefined
时计算为false
。
对于x
所有其他值,它们都评估为真。
也没有性能差异。
2楼
正如您在下表中看到的 JS ==
测试(关注空/未定义的行/列)(src:)没有区别。
因此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 - 您可以在在浏览器中运行测试)
let myVar1=null;
let myVar2=undefined;
3楼
==
和!=
运算符进行“类型转换”以仅比较值本身。
那么不,在这种情况下使用“未定义”或“空”没有区别,两者都代表“空”。
但是如果你使用===
和!==
,它会检查类型和值,而不进行任何类型转换。
两条线的结果将不同。
myVar = null;
console.log(myVar !== undefined) //true
console.log(myVar !== null) //false
4楼
不要混淆和因为它们不是一回事。
空值:
值 null 表示有意缺少任何对象值。 它是 JavaScript 的原始值之一。
不明确的:
尚未赋值的变量的类型为 undefined。 如果正在评估的变量没有赋值,方法或语句也会返回 undefined。 如果未返回值,则函数返回 undefined。
如果变量包含的值既不是null
也不是undefined
,那么您的条件没有区别。
const value = 3; console.log(value !== undefined) //true console.log(value !== null) //true
但是,测试变量是否为null
或undefined
的更好方法是使用!
否定,因为值null
或undefined
将被解析为 true。
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);