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

我的代码如下:

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

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


当前回答

在JavaScript中,据我所知,我们可以检查如下未定义的、空的或空的变量。

if (variable === undefined){
}

if (variable === null){
}

if (variable === ''){
}

检查所有条件:

if(variable === undefined || variable === null || variable === ''){
}

其他回答

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

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

if(typeof value == 'undefined'){

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

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

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

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

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
}