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

我的代码如下:

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

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


当前回答

我在Chrome控制台上运行这个测试。使用(void 0)可以检查undefined:

var c;
undefined
if (c === void 0) alert();
// output =  undefined
var c = 1;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
// check c value  c
// output =  1
if (c === void 0) alert();
// output =  undefined
c = undefined;
// output =  undefined
if (c === void 0) alert();
// output =   undefined

其他回答

最短最简单的:

if(!EmpName ){
 // DO SOMETHING
}

如果EmpName为:

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

同时捕获null和undefined的标准方法是:

if (variable == null) {
     // do something 
}

--这100%等同于更明确但不那么简洁的:

if (variable === undefined || variable === null) {
     // do something 
}

在编写专业JS时,类型平等和==vs==的行为被理解是理所当然的。因此,我们使用==,并且只与null进行比较。


再次编辑

建议使用typeof的评论完全是错误的。是的,如果变量不存在,我上面的解决方案将导致ReferenceError。这是一件好事。这个ReferenceError是可取的:它将帮助您在发布代码之前找到错误并修复它们,就像其他语言中的编译器错误一样。如果您正在处理无法控制的输入,请使用try/catch。

代码中不应该有任何对未声明变量的引用。

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

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
}

让我们看看这个,

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

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

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

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

使用以下解决方案:

const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);

console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...

我可以检查以下内容:

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