如何检查JavaScript中的对象属性是否未定义?


当前回答

“if(window.x){}”是错误安全的

很可能您想要if(window.x)。即使x尚未声明(var x;),该检查也是安全的-浏览器不会抛出错误。

示例:我想知道我的浏览器是否支持历史API

if (window.history) {
    history.call_some_function();
}

工作原理:

window是一个包含所有全局变量作为其成员的对象,尝试访问不存在的成员是合法的。如果x尚未声明或未设置,则window.x返回undefined。undefined在if()求值时导致false。

其他回答

Lodash库中有几个小助手:

isUndefined-检查值是否未定义。

_.isUndefined(undefined) // => true
_.isUndefined(null) // => false

has-检查对象是否包含属性

const object = { 'a': { 'b': 2 } }

_.has(object, 'a.b') // => true
_.has(object, 'a.c') // => false

同样的事情也可以写得更短:

if (!variable){
    // Do it if the variable is undefined
}

or

if (variable){
    // Do it if the variable is defined
}

有一种非常简单的方法。

您可以使用可选链接:

x = {prop:{name:"sajad"}}

console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined

or

if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error

您甚至可以对函数或数组使用可选的链接。

截至2020年年中,这一点尚未得到普遍实施。查看文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

回顾

许多给定的答案给出了错误的结果,因为它们没有区分对象属性不存在的情况和属性值未定义的情况。以下是最流行的解决方案的证明:

让obj={a: 666中,u: undefined//“u”属性的值为“undefined”//“x”属性不存在}console.log('>>>好结果:');console.log('A',obj中的“u”,obj的“x”);console.log('B',obj.hasOwnProperty(“u”),obj.hasOwnProperty(“x”));console.log('\n>>>坏结果:');console.log('C',obj.u==未定义,obj.x==未确定);console.log('D',obj.u==未定义,obj.x==未定义);console.log('E',obj[“u”]==未定义,obj'“x”]===未定义);console.log('F',obj[“u”]==未定义,obj'“x”]===未定义);console.log('G',!obj.u,!obj.x);console.log('H',对象类型u=='未定义',对象的类型x=='不定义');

在《探索JavaScript中的空和未定义的深渊》一文中,我看到Undercore.js等框架使用了这个函数:

function isUndefined(obj){
    return obj === void 0;
}