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

我的代码如下:

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) {
  // If the variable is null or undefined then execution of code will enter here.
}

其他回答

最简单的答案:

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

我刚刚遇到了这个问题,即检查对象是否为空。我只使用这个:

if (object) {
    // Your code
}

例如:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}

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

if(typeof value == 'undefined'){

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

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
}

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

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;
}