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


当前回答

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

[undefined, null].includes(value)

其他回答

与ES5和ES6标准比较undefined或null或0的最佳方法

 if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
    // do something
    }

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

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

一般来说,表达式为:

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

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

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

if (window.variable != null)

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

if (variable != null)

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

if (obj.property != null)

如果If语句的目的是在将值赋给变量之前检查null值或未定义值,则可以使用Nullish Coalescing Operator。根据caniuse的数据,大约85%的浏览器应该支持它(截至2021年1月)。该运算符的示例如下所示:

const a = some_variable ?? '';

这将确保如果some_variable为null或未定义,该变量将被分配给空字符串(或任何其他默认值)。

此操作符最适合您的用例,因为它不会为其他类型的假值(如0和”)返回默认值。

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

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
}