您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在JavaScript中检查“未定义”?

如何在JavaScript中检查“未定义”?

如果您想知道变量是否已声明而无论其值如何,那么使用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

如果您想知道变量是否尚未声明或具有值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 error
Object.defineProperty(window, "myVariable", { 
    get: function() { throw new Error("W00t?"); }, 
    set: undefined 
});
if (myVariable) {
    // Error: W00t?
}
javascript 2022/1/1 18:14:36 有397人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶