如何在JavaScript中检查“undefined”?

3036

在JavaScript中,测试变量是否未定义的最合适方法是什么?

我看到了几种可能的方式:

if (window.myVariable)
或者
if (typeof(myVariable) != "undefined")
或。
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?

9
你想要检查的是仅仅 undefined,还是包括 null - Nick Craver
4
请查看此链接:https://dev59.com/PnVD5IYBdhLWcg3wTJrF。 - Amr Badawy
7
@Robert - 那个问题已经有一个被接受的答案,证明这里的回答都是错误的。 - Daniel Schaffer
3
“Duplicate”是关于对象属性的,因此一些答案并不适用于这个关于变量的问题。 - DCShannon
显示剩余6条评论
16个回答

12

我知道的检查 undefined 最可靠的方法是使用 void 0

这适用于新旧浏览器,且不像某些情况下可以被覆盖的 window.undefined

if( myVar === void 0){
    //yup it's undefined
}

1
这是一种被低估的方法,而且在我看来,它是检查某些东西是否未定义的首选方式。 - Brian M. Hunt
2
完全正确,但我想如果 undefined !== void 0,你可能在代码库中有其他严重的问题。 - Thomas Eding
myVar 没有被先前声明时,它会暴露出抛出错误的情况。 - Kamafeather

8

因为其他回答都没能帮到我,所以我建议这样做。在Internet Explorer 8中,这对我有用:

if (typeof variable_name.value === 'undefined') {
    // variable_name is undefined
}

6
// x has not been defined before
if (typeof x === 'undefined') { // Evaluates to true without errors.
   // These statements execute.
}

if (x === undefined) { // Throws a ReferenceError

}

5

与@Thomas Eding的回答相反:

如果我在代码中忘记声明myVar,那么我会收到myVar未定义的错误信息。

让我们来看一个真实的例子:

我有一个变量名,但我不确定它是否已经被声明过。

然后@Anurag的回答将会有所帮助:

var myVariableToCheck = 'myVar';
if (window[myVariableToCheck] === undefined)
    console.log("Not declared or declared, but undefined.");

// Or you can check it directly 
if (window['myVar'] === undefined) 
    console.log("Not declared or declared, but undefined.");

2
获取 myVar 未定义 错误会是一件“好事”,特别是当你明确写下“如果我忘记声明”时 [重点强调]。在我的代码运行之前就能发现错误,这让我感到非常满意。如果您想了解更多关于我的回答的意见,我已经在我的回答下发表了相关评论。 - Thomas Eding

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

    /* One more thing to understand: typeof ==='undefined' also checks 
       for if a variable is declared, but no value is assigned. In other 
       words, the variable is declared, but not defined. */

    // Will repeat above logic of x for typeof === 'undefined'
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    /* So typeof === 'undefined' works for both, but x === undefined 
       only works for a variable which is at least declared. */

    /* Say if I try using typeof === undefined (not in quotes) for 
       a variable which is not even declared, we will get run a 
       time error. */

    if (z === undefined) {
        alert ("I am neither declared nor defined.")
    };
    // I got this error for z ReferenceError: z is not defined 

1

我将它用作函数参数,并在函数执行时排除它,这样我就可以得到“真正”的未定义。虽然这确实需要你将代码放在一个函数内。我是在阅读jQuery源代码时发现了这个方法。

undefined = 2;

(function (undefined) {
   console.log(undefined); // prints out undefined
   // and for comparison:
   if (undeclaredvar === undefined) console.log("it works!")
})()

当然,你也可以使用 typeof。但是我的所有代码通常都在一个包含函数中,因此使用这种方法可能会在某些地方为我节省一些字节。

4
如果变量undeclaredvar真的未声明,它将会报ReferenceError错误。如果这是一个属性,则会起作用,例如:var undeclaredvar = window.someUndeclaredVar; if (undeclaredvar === undefined) console.log("it works!");请在发布前测试您的示例。 - bartosz.r

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