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


当前回答

无论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

其他回答

类似于你所做的,你可以这样做

If (some_variable === undefined || some_variable === null) { 做的东西 }

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

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

正如在其中一个答案中提到的,如果您谈论的是一个具有全局作用域的变量,那么您可能会很幸运。您可能知道,全局定义的变量往往会被添加到windows对象中。你可以利用这一点假设你要访问一个名为bleh的变量,只需使用双倒操作符(!!)

!!window['bleh'];

这将返回一个false,而bleh还没有被声明和赋值。

无论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

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

一般来说,表达式为:

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

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

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

if (window.variable != null)

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

if (variable != null)

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

if (obj.property != null)