如何检查“未定义"?在JavaScript中? [英] How can I check for "undefined" in JavaScript?
问题描述
测试变量是否在JavaScript中未定义的最合适方法是什么?
What is the most appropriate way to test if a variable is undefined in JavaScript?
我已经看到了几种可能的方法:
I've seen several possible ways:
if (window.myVariable)
或
if (typeof(myVariable) != "undefined")
或
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
推荐答案
如果您有兴趣找出是否已声明变量而无论其值如何,那么使用in
运算符是最安全的方法.考虑以下示例:
If you are interested in finding out whether a variable has been declared regardless of its value, then using the in
operator is the safest way to go. Consider this example:
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
但这在某些情况下可能不是预期的结果,因为已声明但未初始化变量或属性.使用in
运算符进行更可靠的检查.
But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in
operator for a more robust check.
"theFu" in window; // true
"theFoo" in window; // false
如果您想知道变量是否尚未声明或值是否为undefined
,请使用typeof
运算符,该运算符可确保返回字符串:
If you are interested in knowing whether the variable hasn't been declared or has the value undefined
, then use the typeof
operator, which is guaranteed to return a string:
if (typeof myVar !== 'undefined')
与undefined
的直接比较比较麻烦,因为undefined
可能会被覆盖.
Direct comparisons against undefined
are troublesome as undefined
can be overwritten.
window.undefined = "foo";
"foo" == undefined // true
@CMS指出,此问题已在ECMAScript第5版中进行了修补,并且undefined
是不可写的.
As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined
is non-writable.
if (window.myVar)
还将包含这些伪造的值,因此它不是很可靠:
if (window.myVar)
will also include these falsy values, so it's not very robust:
false
0
""
NaN
null
undefined
感谢@CMS指出您的第三种情况-if (myVariable)
在两种情况下也会引发错误.第一个是未定义变量时抛出ReferenceError
的情况.
Thanks to @CMS for pointing out that your third case - if (myVariable)
can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError
.
// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}
另一种情况是变量已定义但具有getter函数,该函数在调用时会引发错误.例如,
The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,
// 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?
}
这篇关于如何检查“未定义"?在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!