I think the most efficient way to test for "value is null
or undefined
" is
(我认为测试“值是否为null
或undefined
”的最有效方法是)
if ( some_variable == null ){
// some_variable is either null or undefined
}
So these two lines are equivalent:
(因此,这两行是等效的:)
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}
Note 1
(注1)
As mentioned in the question, the short variant requires that some_variable
has been declared, otherwise a ReferenceError will be thrown.
(正如问题中提到的那样,简短变体要求声明了some_variable
,否则将引发ReferenceError。)
However in many use cases you can assume that this is safe:(但是,在许多用例中,您可以假定这是安全的:)
check for optional arguments:
(检查可选参数:)
function(foo){
if( foo == null ) {...}
check for properties on an existing object
(检查现有对象的属性)
if(my_obj.foo == null) {...}
On the other hand typeof
can deal with undeclared global variables (simply returns undefined
).
(另一方面, typeof
可以处理未声明的全局变量(仅返回undefined
)。)
Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.(正如Alsciende解释的那样,出于充分的原因,这些案例应该减少到最少。)
Note 2
(笔记2)
This - even shorter - variant is not equivalent:
(这个-甚至更短-的变体并不等效:)
if ( !some_variable ) {
// some_variable is either null, undefined, 0, NaN, false, or an empty string
}
so
(所以)
if ( some_variable ) {
// we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}
Note 3
(注3)
In general it is recommended to use ===
instead of ==
.
(通常,建议使用===
代替==
。)
The proposed solution is an exception to this rule.(提议的解决方案是该规则的例外。)
The JSHint syntax checker even provides the eqnull
option for this reason.(为此, eqnull
语法检查器甚至提供了eqnull
选项。)
From the jQuery style guide :
(从jQuery样式指南 :)
Strict equality checks (===) should be used in favor of ==.
(应该使用严格的相等性检查(===)来支持==。)
The only exception is when checking for undefined and null by way of null.(唯一的例外是通过null检查undefined和null时。)
// Check for both undefined and null values, for some important reason. undefOrNull == null;