我该如何确定一个变量是“未定义”还是“空值(null)”?

2663

如何判断变量是undefined还是null

我的代码如下:

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

<div id="esd-names">
  <div id="name"></div>
</div>

但是当我这样做时,JavaScript解释器会停止执行。


可能是如何在JavaScript中检查空字符串?的重复问题。 - T.Todua
使用内置的空值合并运算符(??) - Dennis Nolan
@DennisNolan 这个问题是在2010年提出的。 - not my real name
如果(EmpName == 'undefined')将不会测试EmpName是否未定义,它将测试字符串“undefined”,因此去掉那些单引号:如果(EmpName == undefined)//因为没有引号的'undefined'是未定义的或者更简单的如果(!EmpName){ // 做一些事情 }; - user7394313
35个回答

3

我在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

2

我使用以下代码来测试变量是否为null或未定义。

    if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
      console.log('variable is undefined or null');
    }

接近了但不太对。去掉 typeof 直接与 undefined 进行比较,而不是将其作为字符串。这样可以工作,但额外的运算符只会使它变得啰嗦。 - temporary_user_name
在这种情况下,是的,你是对的,我们不需要使用typeof。但是当你处理未定义的变量时,使用typeof是一个好习惯。使用typeof的一个原因是,如果变量没有被声明,它不会抛出错误。 - DanKodi
那其实是一件坏事。你不想在代码中有未声明的变量。你希望它抛出一个ReferenceError,这样你就可以找到这个变量并声明它。当然,在像C++这样的编译语言中,你不会尝试这样做!仅仅因为JS允许这样做,并不意味着应该这样做。 - temporary_user_name
1
你的或语句是反向的。检查某个变量是否未定义应该是第一步,而不是第二步。 - Anthony Rutledge

2
(null == undefined)  // true

(null === undefined) // false

因为 === 检查类型和值。虽然两个类型不同,但值相同。


2

foo == null 检查应该能够以最短的方式解决“未定义或空值”的情况。(不考虑“foo未声明”的情况。)但是,习惯使用3个等号(作为最佳实践)的人可能不会接受它。只需查看 eslint 和 tslint 中的 eqeqeqtriple-equals 规则即可了解情况...

在这种情况下,应该采用显式方法,即分别检查变量是否为 undefinednull,而我对这个主题的贡献(目前有27个非负答案!)是使用 void 0 作为既简短又安全的方法来执行对 undefined 的检查。

使用foo === undefined不安全,因为undefined不是保留字并且可能被屏蔽(MDN)。使用typeof === 'undefined'检查是安全的,但如果我们不关心foo未声明的情况,则可以使用以下方法:
if (foo === void 0 || foo === null) { ... }

2

让我们来看一下这个:

  1.  

    let apple; // Only declare the variable as apple
    alert(apple); // undefined
    

    In the above, the variable is only declared as apple. In this case, if we call method alert it will display undefined.

  2.  

       let apple = null; /* Declare the variable as apple and initialized but the value is null */
       alert(apple); // null
    
在第二个例子中,它显示 null,因为变量 apple 的值是 null。
所以你可以检查一个值是否未定义或为空。
if(apple !== undefined || apple !== null) {
    // Can use variable without any error
}

1

我认为你可以这样做,这样在一个条件语句中检查同一变量的多个值会更有效率。

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
}

1

如果您喜欢沿用 === 运算符并且希望代码更加明确,您也可以使用 (value ?? null) === null


到目前为止,有三种方法。

  • value == null
  • value === null || value === undefined
  • (value ?? null) === null

我通常避免使用==,但这次我更喜欢== null


@noseratio-opentowork 好的,你否定它就可以了。 - Константин Ван
1
也许我有所遗漏,但是你为什么需要使用 Symbol() 呢❓ 为什么不直接使用 (a ?? null) === null ❓ 或者 (a ?? undefined) === undefined - noseratio - open to work
1
@noseratio-opentowork 感谢您指出这个问题。我不必要地过于复杂化了它,而且当我写它的时候我自己也无法理解。也许我试图检查它是否合并到第二个操作数中。 - Константин Ван

0
调用typeof null返回一个值“object”,因为特殊值null被认为是一个空对象引用。 Safari版本5和Chrome版本7之前有一个怪癖,在正则表达式上调用typeof返回“function”,而所有其他浏览器都返回“object”。

0
var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

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


0
var i;

if (i === null || typeof i === 'undefined') {
    console.log(i, 'i is undefined or null')
}
else {
    console.log(i, 'i has some value')
}

3
如果用户输入单词“undefined”,会发生什么? - Chuck
你的问题很好,它表明条件是真实的,因此我们需要将选项“normal undefined”更改为typeof条件。@Chuck - KARTHIKEYAN.A
这是错误的。 typeof 永远不会产生 undefined,只会产生字符串 'undefined'。此外,如果 iundefined,则 i == null 已经为真,因此即使第二个布尔值有效,它也会变得多余。 - temporary_user_name
2
这个解决方案(条件被反转)已经在2013年10月11日由 @jkindwall 提供。stackoverflow.com/a/19323555/2943403 这篇仅包含代码的帖子是完全无用的,因为它没有给页面增加任何新价值。事实上,它增加了页面的负担,浪费了研究人员阅读它的时间。请删除这个答案。 - mickmackusa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接