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

我的代码如下:

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(!EmpName){
  // DO SOMETHING
};

其他回答

jQuery检查元素不为空:

var dvElement = $('#dvElement');

if (dvElement.length  > 0) {
    // Do something
}
else{
    // Else do something else
}
if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}
var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

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

我仍然认为测试这两个条件的最佳/安全方法是将值转换为字符串:

var EmpName = $("div#esd-names div#name").attr('class');

// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
    // Do something with your code
}

// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
    // Do something with your code
}

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

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