类型检查vs空检查

Typeof check vs null check

本文关键字:检查 vs 类型      更新时间:2023-09-26

我学会了像这样检查Javascript中的变量:

function x(variable){
   if(typeof variable !== "undefined" && variable !== null)...
}

一位新同事现在说这样做更容易、更好:

function x(variable){
   if(variable != null)
}

这真的一样吗?这是怎么做到的?

谢谢

Null和undefined是JavaScript中的两种基本数据类型。


来自Mozilla MDN的示例:

var x;
if (x === undefined) {
   // these statements execute
}
else {
   // these statements do not execute
}

这里必须使用严格相等运算符而不是标准相等运算符,因为x == undefined也检查x是否为空,而严格相等不检查。null不等于undefined


function x(variable){
   if(variable != null) // variable would be both null and undefined for comparison
}
我认为上面的例子是有效的,因为你没有使用严格的比较。所以简而言之,你的两个例子不一样,但可以给出相同的结果。这完全取决于您的逻辑要求是否是严格的比较。

function x(variable){ if(typeof variable !== "undefined" && variable !== null)... }

上面的

将检查变量is是否存在或是否已声明,如果存在则不为空。如果你不确定变量的声明,这是一个很好的方法。

function x(variable){ if(variable != null) }

上面的

将检查变量是否为空。只有当您确定变量在第一个位置声明时,这才有用。

额外

,

return value === null || value === undefined;
上面的

表示null或undefined。

希望对你有帮助。

干杯!

唯一的区别是第一个可以安全地用于检查全局变量

> foo // -> ReferenceError
> foo != null // -> ReferenceError
> typeof foo !== 'undefined' && foo !== null // -> false

但是在你的例子中,这并不重要,因为空函数参数总是undefined