如果您想知道变量是否已声明而无论其值如何,那么使用
in运算符是最安全的方法。考虑以下示例:
// global scopevar theFu; // theFu has been declared, but its value is undefinedtypeof theFu; // "undefined"
但这在某些情况下可能不是预期的结果,因为已声明但未初始化变量或属性。使用
in运算符进行更强大的检查。
"theFu" in window; // true"theFoo" in window; // false
如果您想知道变量是否尚未声明或具有值
undefined,请使用
typeof运算符,该运算符可确保返回字符串:
if (typeof myVar !== 'undefined')
直接比较比较
undefined麻烦,
undefined可能会被覆盖。
window.undefined = "foo";"foo" == undefined // true
正如@CMS指出的那样,此问题已在ECMAscript第5版中进行了修补,并且
undefined不可写。
if (window.myVar)还将包含这些虚假值,因此它不是很可靠:
false
0
“”
NaN
null
undefined
第三种情况-
if (myVariable)在两种情况下也会引发错误。第一种是未定义变量时抛出
ReferenceError。
// abc was never declared.if (abc) { // ReferenceError: abc is not defined}另一种情况是已定义变量,但是具有getter函数,该函数在调用时会引发错误。例如,
// or it's a property that can throw an errorObject.defineProperty(window, "myVariable", { get: function() { throw new Error("W00t?"); }, set: undefined });if (myVariable) { // Error: W00t?}


