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

我的代码如下:

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 x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

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

其他回答

var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

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

由于使用的是jQuery,因此可以通过使用单个函数来确定变量是未定义的还是其值为空。

var s; // undefined
jQuery.isEmptyObject(s); // will return true;

s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;

// usage
if(jQuery.isEmptyObject(s)){
    alert('Either variable: s is undefined or its value is null');
}else{
     alert('variable: s has value ' + s);
}

s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
if (typeof EmpName != 'undefined' && EmpName) {

如果值不是:

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

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

if(typeof value == 'undefined'){

如果创建一个函数来检查它:

export function isEmpty (v) {
 if (typeof v === "undefined") {
   return true;
 }
 if (v === null) {
   return true;
 }
 if (typeof v === "object" && Object.keys(v).length === 0) {
   return true;
 }

 if (Array.isArray(v) && v.length === 0) {
   return true;
 }

 if (typeof v === "string" && v.trim().length === 0) {
   return true;
 }

return false;
}