如果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
}

其他回答

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

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

}

就我个人而言,我总是使用以下方法:

var x;
if( x === undefined) {
    //Do something here
}
else {
   //Do something else here
}

window.undefined属性在所有现代浏览器(JavaScript 1.8.5或更高版本)中都是不可写的。Mozilla文档中:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined,我看到了这一点:使用typeof()的一个原因是,如果尚未定义变量,它不会抛出错误。

我更喜欢使用

x === undefined 

因为如果x之前没有声明过,它会失败并在我面前爆炸,而不是默默地通过/失败。这提醒我x未声明。我认为JavaScript中使用的所有变量都应该声明。

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

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

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

if (typeof something != "undefined") {
    // ...
}

在本文中,我了解到Undercore.js等框架使用此函数:

function isUndefined(obj){
    return obj === void 0;
}