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


当前回答

使用严格比较运算符可以很容易地区分这两个值。

示例代码:

function compare(){
    var a = null; //variable assigned null value
    var b;  // undefined
    if (a === b){
        document.write("a and b have same datatype.");
    }
    else{
        document.write("a and b have different datatype.");
    }   
}

其他回答

无论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((someObject.someMember ?? null) === null) {
  // bladiebla
}

正在发生的事情非常清楚,很难被误解。这是非常重要的!: -)

这个使用??运营商(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)。如果someObject的值。somember为空或未定义,则??运算符介入并将值置为空。

TBH,我喜欢这个东西的明确性,但我通常更喜欢someObject。somember == null,它更有可读性,熟练的JS开发人员可能知道这里发生了什么。

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

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

在浏览器中打开开发人员工具,并尝试如下图所示的代码。

您可以使用lodash库。

_.isNil(value)对于null和undefined都给出true

测试地址:https://bazinga.tools/lodash