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

我的代码如下:

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

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


当前回答

foo==null检查应该能做到这一点,并以最短的方式解决“undefined OR null”情况。(不考虑“foo is Not declarated”的情况。)但习惯于使用3等于(作为最佳实践)的人可能不会接受它。只需看看eslint和tslint中的eqeqeq或三等于规则。。。

在这种情况下,当我们分别检查变量是否未定义或为空时,应采用显式方法,我对本主题的贡献(目前有27个非否定答案!)是使用void 0作为执行未定义检查的简短而安全的方法。

使用foo==undefined是不安全的,因为undefineed不是保留字,可以被隐藏(MDN)。使用typeof==“undefined”检查是安全的,但如果我们不关心foo是否未声明,则可以使用以下方法:

if (foo === void 0 || foo === null) { ... }

其他回答

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

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

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

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

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


再次编辑

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

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

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

if (object) {
    // Your code
}

例如:

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

由于使用的是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 (x === null || x === undefined) {
 // Add your response code here, etc.
}

来源:https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/

最佳方式:

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

/* do your stuff */
}