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

我的代码如下:

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

同时捕获null和undefined的标准方法是:

if (variable == null) {
     // do something 
}

--这100%等同于更明确但不那么简洁的:

if (variable === undefined || variable === null) {
     // do something 
}

在编写专业JS时,类型平等和==vs==的行为被理解是理所当然的。因此,我们使用==,并且只与null进行比较。


再次编辑

建议使用typeof的评论完全是错误的。是的,如果变量不存在,我上面的解决方案将导致ReferenceError。这是一件好事。这个ReferenceError是可取的:它将帮助您在发布代码之前找到错误并修复它们,就像其他语言中的编译器错误一样。如果您正在处理无法控制的输入,请使用try/catch。

代码中不应该有任何对未声明变量的引用。

最简单的检查方法是:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}

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

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
}

您可以通过简单地使用typeof:

if(typeof value == 'undefined'){