如何确定变量是未定义的还是空的?

我的代码如下:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>

但如果我这样做,JavaScript解释器将停止执行。


当前回答

为了测试变量是否为空或未定义,我使用以下代码。

    if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
      console.log('variable is undefined or null');
    }

其他回答

调用typeof null返回“object”值,因为特殊值null被认为是空对象引用。Safari到第5版和Chrome到第7版都有一个怪癖,在正则表达式上调用typeof返回“function”,而所有其他浏览器都返回“object”。

var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

您只能使用第二个:因为它将检查定义和声明

让我们看看这个,

 让苹果;//只将变量声明为apple警报(苹果);//未定义在上文中,变量仅声明为apple。在这种情况下,如果我们调用方法alert,它将显示undefined。 让apple=null;/*将变量声明为apple并初始化,但值为空*/警报(苹果);//无效的

第二个显示为空,因为apple值的变量为空。

因此,您可以检查值是未定义的还是空的。

if(apple !== undefined || apple !== null) {
    // Can use variable without any error
}

结合以上答案,似乎最完整的答案是:

if( typeof variable === 'undefined' || variable === null ){
    // Do stuff
}

这应该适用于任何未声明或已声明且显式设置为null或undefined的变量。对于具有实际非空值的任何声明变量,布尔表达式的计算结果应为false。

由于使用的是jQuery,因此可以通过使用单个函数来确定变量是未定义的还是其值为空。

var s; // undefined
jQuery.isEmptyObject(s); // will return true;

s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;

// usage
if(jQuery.isEmptyObject(s)){
    alert('Either variable: s is undefined or its value is null');
}else{
     alert('variable: s has value ' + s);
}

s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;