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

我见过几种可能的方法:

if (window.myVariable)

Or

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

Or

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

当前回答

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

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

其他回答

如果未定义,它将不等于包含字符“undefined”的字符串,因为该字符串未定义。

您可以检查变量的类型:

if (typeof(something) != "undefined") ...

有时你甚至不必检查类型。如果变量的值在设置时不能求值为false(例如,如果它是一个函数),那么可以只对变量求值。例子:

if (something) {
  something(param);
}
    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 
if (typeof foo == 'undefined') {
 // Do something
};

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

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

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

}

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