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

我见过几种可能的方法:

if (window.myVariable)

Or

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

Or

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

当前回答

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

这与较新和较旧的浏览器都兼容,并且不能像window那样被覆盖。在某些情况下,未定义的浏览器可以被覆盖。

if( myVar === void 0){
    //yup it's 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 

我个人使用

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%的时间里,==未定义(和***咳嗽***类型)工作正常。如果你真的关心,你可以单独阅读这个主题。)

与@Thomas Eding的回答相反:

如果我忘记在代码中声明myVar,那么我将得到myVar未定义。

让我们举一个真实的例子:

我有一个变量名,但我不确定它是否在某处声明。

那么@Anurak的回答会有所帮助:

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.");

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

这与较新和较旧的浏览器都兼容,并且不能像window那样被覆盖。在某些情况下,未定义的浏览器可以被覆盖。

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

由于其他答案对我都没有帮助,我建议这样做。它在Internet Explorer 8中对我有效:

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