如果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?
当前回答
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
}
其他回答
如果您有兴趣了解变量是否已声明,而不管其值如何,那么使用in运算符是最安全的方法。考虑以下示例:
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
但在某些情况下,这可能不是预期的结果,因为变量或属性已声明,但尚未初始化。使用in运算符进行更稳健的检查。
"theFu" in window; // true
"theFoo" in window; // false
如果您想知道变量是否尚未声明或值未定义,请使用typeof运算符,它保证返回字符串:
if (typeof myVar !== 'undefined')
与undefined的直接比较很麻烦,因为undefineed可以被覆盖。
window.undefined = "foo";
"foo" == undefined // true
正如@CMS所指出的,这已经在ECMAScript第5版中修补,undefined是不可写的。
if(window.myVar)也将包含这些虚假值,因此它不是很健壮:
false 0 "" NaN null undefined
感谢@CMS指出您的第三种情况-if(myVariable)在两种情况下也会抛出错误。第一种情况是尚未定义引发ReferenceError的变量。
// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}
另一种情况是定义了变量,但有一个getter函数,在调用时抛出错误。例如
// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if (myVariable) {
// Error: W00t?
}
就我个人而言,我总是使用以下方法:
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中使用的所有变量都应该声明。
if (typeof foo == 'undefined') {
// Do something
};
注意,在这种情况下不需要严格比较(!==),因为typeof将始终返回字符串。
与@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.");
// x has not been defined before
if (typeof x === 'undefined') { // Evaluates to true without errors.
// These statements execute.
}
if (x === undefined) { // Throws a ReferenceError
}