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

我的代码如下:

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 == null) {
    // Do stuff, will only match null or undefined, this won't match false
}

其他回答

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

SO,

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

相当于:

EmpName ??= 'some value';
if (typeof EmpName != 'undefined' && EmpName) {

如果值不是:

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

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

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

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

请参阅JavaScript最佳实践。

if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}