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

我的代码如下:

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

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


当前回答

让我们看看这个,

 让苹果;//只将变量声明为apple警报(苹果);//未定义在上文中,变量仅声明为apple。在这种情况下,如果我们调用方法alert,它将显示undefined。 让apple=null;/*将变量声明为apple并初始化,但值为空*/警报(苹果);//无效的

第二个显示为空,因为apple值的变量为空。

因此,您可以检查值是未定义的还是空的。

if(apple !== undefined || apple !== null) {
    // Can use variable without any error
}

其他回答

通过最新的javascript更改,您可以使用新的逻辑运算符??=检查左操作数是否为空或未定义,如果为空,则分配右操作数的值。

SO,

if(EmpName == null){  // if Variable EmpName null or undefined
  EmpName = 'some value';
};

相当于:

EmpName ??= 'some value';

让我们看看这个,

 让苹果;//只将变量声明为apple警报(苹果);//未定义在上文中,变量仅声明为apple。在这种情况下,如果我们调用方法alert,它将显示undefined。 让apple=null;/*将变量声明为apple并初始化,但值为空*/警报(苹果);//无效的

第二个显示为空,因为apple值的变量为空。

因此,您可以检查值是未定义的还是空的。

if(apple !== undefined || apple !== null) {
    // Can use variable without any error
}
var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

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

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

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
}
if (typeof EmpName != 'undefined' && EmpName) {

如果值不是:

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