如果JavaScript中未定义变量,最合适的测试方法是什么?
我见过几种可能的方法:
if (window.myVariable)
Or
if (typeof(myVariable) != "undefined")
Or
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
如果JavaScript中未定义变量,最合适的测试方法是什么?
我见过几种可能的方法:
if (window.myVariable)
Or
if (typeof(myVariable) != "undefined")
Or
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
当前回答
与@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.");
其他回答
由于其他答案对我都没有帮助,我建议这样做。它在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;
}
如果未定义,它将不等于包含字符“undefined”的字符串,因为该字符串未定义。
您可以检查变量的类型:
if (typeof(something) != "undefined") ...
有时你甚至不必检查类型。如果变量的值在设置时不能求值为false(例如,如果它是一个函数),那么可以只对变量求值。例子:
if (something) {
something(param);
}
我知道检查undefined最可靠的方法是使用void 0。
这与较新和较旧的浏览器都兼容,并且不能像window那样被覆盖。在某些情况下,未定义的浏览器可以被覆盖。
if( myVar === void 0){
//yup it's undefined
}