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

我的代码如下:

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

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

请参阅JavaScript最佳实践。

其他回答

如果要检查的变量是全局变量,请执行

if (window.yourVarName) {
    // Your code here
}

即使yourVarName变量不存在,这种检查方法也不会引发错误。

示例:我想知道我的浏览器是否支持历史API

if (window.history) {
    history.back();
}

工作原理:

窗口是一个对象,它保存所有全局变量作为其财产,在JavaScript中,尝试访问一个不存在的对象属性是合法的。如果历史记录不存在,则window.history返回undefined。undefined为false,因此if(undefineed){}块中的代码不会运行。

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

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

if (i === null || typeof i === 'undefined') {
    console.log(i, 'i is undefined or null')
}
else {
    console.log(i, 'i has some value')
}
var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

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

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

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

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