我们经常在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的一种(不必要的)行为,还是这两种方式之间真的有一些区别?


当前回答

你可以检查变量是否有值。的含义,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

如果您不知道一个变量是否存在(也就是说,它是否声明过),您应该使用typeof操作符进行检查。如。

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}

其他回答

这是一个非常罕见的例子,建议使用==而不是===。表达式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 },
]);

无论yyy是undefined还是null,它都会返回true

if (typeof yyy == 'undefined' || !yyy) {
    console.log('yes');
} else {
    console.log('no');
}

yes

if (!(typeof yyy == 'undefined' || !yyy)) {
    console.log('yes');
} else {
    console.log('no');
}

no

下面是另一种使用Array includes()方法的方法:

[undefined, null].includes(value)

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

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;

如果您试图引用一个未声明的变量,那么在所有JavaScript实现中都会抛出一个错误。

对象的属性不受相同条件的约束。如果未定义对象属性,则在尝试访问它时不会抛出错误。在这种情况下,你可以缩短:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property != null)

考虑到这一点,以及全局变量可以作为全局对象(浏览器中的窗口)的属性访问的事实,你可以对全局变量使用以下方法:

if (window.some_variable != null) {
    // Do something with some_variable
}

在局部作用域中,确保变量在代码块的顶部声明总是有用的,这将节省重复使用typeof。