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

我的代码如下:

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

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


当前回答

jQuery检查元素不为空:

var dvElement = $('#dvElement');

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

其他回答

最简单的检查方法是:

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

您可以使用抽象相等运算符的特性来执行此操作:

if (variable == null){
    // your code here.
}

因为null==undefined为true,所以上面的代码将捕获null和undefineed。

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

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

请参阅JavaScript最佳实践。

使用以下解决方案:

const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);

console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...

我可以检查以下内容:

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

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

if(typeof value == 'undefined'){