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

我见过几种可能的方法:

if (window.myVariable)

Or

if (typeof(myVariable) != "undefined")

Or

if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?

当前回答

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

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

}

其他回答

if (typeof foo == 'undefined') {
 // Do something
};

注意,在这种情况下不需要严格比较(!==),因为typeof将始终返回字符串。

2020年更新

我倾向于检查类型(即,可以重新定义未定义的)的原因之一与ECMAScript 5的大量采用无关。另一个,你可以使用typeof来检查未声明变量的类型,总是小众的。因此,我现在建议在大多数情况下使用直接比较:

myVariable === undefined

2010年的原始答案

我喜欢使用typeof。当变量从未声明时,它将起作用,这与使用if.与==或==运算符或类型强制进行的任何比较不同(undefined,与null不同,也可能在ECMAScript 3环境中重新定义,这使得它不可靠,尽管现在几乎所有常见环境都符合ECMAScript5或更高版本)。

if (typeof someUndeclaredVariable == "undefined") {
    // Works
}

if (someUndeclaredVariable === undefined) { 
    // Throws an error
}

我个人使用

myVar === undefined

警告:请注意==用于==,并且myVar先前已声明(未定义)。


我不喜欢myVar==“undefined”的类型。我认为这是长篇大论,没有必要。(我可以用更少的代码完成同样的任务。)

现在有些人读到这篇文章时,会痛苦万分,尖叫道:“等等!WAAITT!!!undefined可以被重新定义!”

凉的我知道这一点。同样,Javascript中的大多数变量都可以重新定义。你应该永远不要使用任何可以重新定义的内置标识符吗?

如果你遵循这条规则,对你有好处:你不是伪君子。

问题是,为了在JS中做大量的实际工作,开发人员需要依赖于可重新定义的标识符。我没有听到有人告诉我我不应该使用setTimeout,因为有人可以

window.setTimeout = function () {
    alert("Got you now!");
};

总之,不使用原始==undefined的“它可以被重新定义”参数是假的。

(如果您仍然害怕未定义被重新定义,为什么要盲目地将未经测试的库代码集成到代码库中?或者更简单:一个linting工具。)


此外,与typeof方法一样,该技术可以“检测”未声明的变量:

if (window.someVar === undefined) {
    doSomething();
}

但这两种技术在抽象方面都存在漏洞。我劝你不要用这个甚至

if (typeof myVar !== "undefined") {
    doSomething();
}

考虑:

var iAmUndefined;

要获取该变量是否已声明,可能需要使用in运算符。(在许多情况下,您可以简单地读取代码O_O)。

if ("myVar" in window) {
    doSomething();
}

但是等等!还有更多!如果一些原型连锁魔法正在发生…?现在,即使是高级操作员也不够。(好吧,我已经完成了这一部分的工作,只是说99%的时间里,==未定义(和***咳嗽***类型)工作正常。如果你真的关心,你可以单独阅读这个主题。)

您可以使用typeof,如下所示:

if (typeof something != "undefined") {
    // ...
}
    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