我们经常在JavaScript代码中使用以下代码模式

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

是否有一种不那么冗长的检查方法具有相同的效果?

根据一些论坛和文献,简单地说下面应该有同样的效果。

if (some_variable)
{
    // Do something with some_variable
}

不幸的是,当some_variable未定义时,Firebug在运行时将这样的语句计算为错误,而第一个语句对它来说很好。这仅仅是Firebug的一种(不必要的)行为,还是这两种方式之间真的有一些区别?


当前回答

你必须定义一个这样的函数:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}

其他回答

首先,你必须清楚你要测试什么。JavaScript有各种各样的隐式转换会让您出错,还有两种不同类型的相等比较器:==和===。

测试null或未定义的函数test(val)应具有以下特征:

 test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

让我们来看看哪些想法实际上通过了我们的测试。

这些工作:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

这些都不起作用:

typeof(val) === 'undefined'
!!val

我创建了一个jsperf条目来比较这些方法的正确性和性能。目前的结果还不确定,因为在不同的浏览器/平台上还没有足够的运行。请花一分钟在你的电脑上运行测试!

目前,简单的val == null测试似乎提供了最好的性能。它也是最短的。如果您想要补码,测试可以被反求为val != null。

由于没有一个完整而正确的答案,我将尝试总结:

一般来说,表达式为:

if (typeof(variable) != "undefined" && variable != null)

不能简化,因为变量可能没有声明,因此省略typeof(variable) != "undefined"将导致ReferenceError。但是,你可以根据上下文来简化表达式:

如果变量是全局的,你可以简化为:

if (window.variable != null)

如果它是局部的,你可以避免这个变量未声明的情况,也可以简化为:

if (variable != null)

如果它是object属性,你不必担心ReferenceError:

if (obj.property != null)

我认为最有效的测试“值为空或未定义”的方法是

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可以处理未声明的全局变量(只是返回未定义)。然而,正如Alsciende解释的那样,出于充分的理由,这些病例应该减少到最低限度。

注2

这个更短的变体是不等价的:

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 ""
}

注3

一般情况下,建议使用===代替==。 建议的解决方案是这条规则的一个例外。为此,JSHint语法检查器甚至提供了eqnull选项。

jQuery风格指南:

严格的相等性检查(===)应该用于==。唯一的 异常是在检查undefined和null时通过null的方式。

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

2021 - 03年编辑:

现在大多数浏览器 支持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;

这是一个非常罕见的例子,建议使用==而不是===。表达式somevar == null对于undefined和null将返回true,但对于其他所有内容将返回false(如果变量未声明则会出现错误)。

如预期的那样,使用!=将翻转结果。

现代编辑器不会对使用==或!=操作符加null发出警告,因为这几乎总是需要的行为。

最常见的比较:

undeffinedVar == null     // true
obj.undefinedProp == null // true
null == null              // true
0 == null                 // false
'0' == null               // false
'' == null                // false

自己试试吧:

let undefinedVar;
console.table([
    { test : undefinedVar,     result: undefinedVar     == null },
    { test : {}.undefinedProp, result: {}.undefinedProp == null },
    { test : null,             result: null             == null },
    { test : false,            result: false            == null },
    { test : 0,                result: 0                == null },
    { test : '',               result: ''               == null },
    { test : '0',              result: '0'              == null },
]);

你必须区分不同的情况:

变量可以是未定义的或未声明的。如果在typeof以外的任何上下文中访问未声明的变量,将会得到一个错误。

if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

已声明但未初始化的变量是未定义的。

let foo;
if (foo) //evaluates to false because foo === undefined

Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact: value = obj.prop || defaultValue which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue". Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead value = ('prop' in obj) ? obj.prop : defaultValue