在JavaScript中,测试变量是否未定义的最合适方法是什么?
我看到了几种可能的方式:
if (window.myVariable)
或者if (typeof(myVariable) != "undefined")
或。if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
在JavaScript中,测试变量是否未定义的最合适方法是什么?
我看到了几种可能的方式:
if (window.myVariable)
或者if (typeof(myVariable) != "undefined")
或。if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
我知道的检查 undefined
最可靠的方法是使用 void 0
。
这适用于新旧浏览器,且不像某些情况下可以被覆盖的 window.undefined
。
if( myVar === void 0){
//yup it's undefined
}
undefined !== void 0
,你可能在代码库中有其他严重的问题。 - Thomas EdingmyVar
没有被先前声明时,它会暴露出抛出错误的情况。 - Kamafeather因为其他回答都没能帮到我,所以我建议这样做。在Internet Explorer 8中,这对我有用:
if (typeof variable_name.value === 'undefined') {
// variable_name is 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
}
与@Thomas Eding的回答相反:
如果我在代码中忘记声明myVar
,那么我会收到myVar未定义
的错误信息。
让我们来看一个真实的例子:
我有一个变量名,但我不确定它是否已经被声明过。
然后@Anurag的回答将会有所帮助:
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.");
myVar 未定义
错误会是一件“好事”,特别是当你明确写下“如果我忘记声明”时 [重点强调]。在我的代码运行之前就能发现错误,这让我感到非常满意。如果您想了解更多关于我的回答的意见,我已经在我的回答下发表了相关评论。 - Thomas Eding 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
我将它用作函数参数,并在函数执行时排除它,这样我就可以得到“真正”的未定义。虽然这确实需要你将代码放在一个函数内。我是在阅读jQuery源代码时发现了这个方法。
undefined = 2;
(function (undefined) {
console.log(undefined); // prints out undefined
// and for comparison:
if (undeclaredvar === undefined) console.log("it works!")
})()
typeof
。但是我的所有代码通常都在一个包含函数中,因此使用这种方法可能会在某些地方为我节省一些字节。var undeclaredvar = window.someUndeclaredVar;
if (undeclaredvar === undefined) console.log("it works!");
请在发布前测试您的示例。 - bartosz.r
undefined
,还是包括null
? - Nick Craver