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

我的代码如下:

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 (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}

其他回答

最短最简单的:

if(!EmpName ){
 // DO SOMETHING
}

如果EmpName为:

无效的未定义NaN公司空的字符串(“”)0假的

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

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

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

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

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 variable==='undefined' || variable===null) {

/* do your stuff */
}

我刚刚遇到了这个问题,即检查对象是否为空。我只使用这个:

if (object) {
    // Your code
}

例如:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}