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

我的代码如下:

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

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


当前回答

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

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
}

其他回答

jQuery检查元素不为空:

var dvElement = $('#dvElement');

if (dvElement.length  > 0) {
    // Do something
}
else{
    // Else do something else
}

最简单的答案:

if(!EmpName){
  // DO SOMETHING
};

你可以这样做,我认为在一个条件下对同一变量进行多值检查更有效

const x = undefined;
const y = null;
const z = 'test';

if ([undefined, null].includes(x)) {
  // Will return true
}

if ([undefined, null].includes(y)) {
  // Will return true
}

if ([undefined, null].includes(z)) {
  // Will return false
}

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

if(x==null)在JavaScript中是个坏主意。使用“==”判断-它可能会导致意外的类型强制,并且CoffeeScript无法读取它,决不能在条件判断中使用“==”或“!=”!

if(x)会更好,但要注意0和“”。它将被视为false,而不是“!=null”的equal方法为true。

请参阅JavaScript最佳实践。