我认为测试“价值是null
或undefined
”的最有效方法是
if ( some_variable == null ){
// some_variable is either null or undefined
}
所以这两行是等价的:
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}
注1
如问题中所述,短变体要求some_variable
已声明,否则将引发ReferenceError。但是,在许多用例中,您可以假设这是安全的:
检查可选参数:
function(foo){
if( foo == null ) {...}
检查现有对象的属性
if(my_obj.foo == null) {...}
另一方面typeof
可以处理未声明的全局变量(简单地返回undefined
)。然而,正如 Alsciende 解释的那样,出于充分的理由,这些案例应该减少到最低限度。
笔记2
这个 - 甚至更短 - 变体是不等价的:
if ( !some_variable ) {
// some_variable is either null, undefined, 0, NaN, false, or an empty string
}
所以
if ( some_variable ) {
// we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}
注3
一般来说,建议使用===
而不是==
. 建议的解决方案是该规则的一个例外。JSHint语法检查器甚至eqnull
为此提供了选项。
来自jQuery 风格指南:
应该使用严格的相等检查 (===) 来支持 ==。唯一的例外是在通过 null 检查未定义和 null 时。
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
编辑 2021-03:
现在大多数浏览器都
支持Nullish 合并运算符 ( ??
)
和Logical nullish assignment(??=)
,如果变量为 null 或未定义,则可以更简洁地分配默认值,例如:
if (a.speed == null) {
// Set default if null or undefined
a.speed = 42;
}
可以写成这些形式中的任何一种
a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;