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

我的代码如下:

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){
    // your code here.
}

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

其他回答

您可以简单地使用以下方法(我知道有更短的方法可以做到这一点,但这可能会使视觉观察更容易,至少对其他查看代码的人来说是如此)。

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 (variable == null){
    // your code here.
}

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

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

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

如果值不是:

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

让我们看看这个,

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

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

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

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