如何检查“未定义”在JavaScript? [英] How to 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?
推荐答案
如果您有兴趣了解变量是否有变量已声明无论其值如何,然后在运算符中使用是最安全的方法。考虑这个例子。
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"
但这可能不是某些情况下的预期结果,因为变量或属性已声明但尚未初始化。使用运算符中的进行更强大的检查。
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.
if (typeof myVar !== 'undefined')
typeof
运算符保证返回一个字符串。直接比较 undefined
很麻烦,因为 undefined
可以被覆盖。
The typeof
operator is guaranteed to return a string. Direct comparisons against undefined
are troublesome as undefined
can be overwritten.
window.undefined = "omg";
"omg" == 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屋!