如何检查JavaScript中的对象属性是否未定义?
当前回答
我想向您展示我正在使用的一些东西,以保护未定义的变量:
Object.defineProperty(window, 'undefined', {});
这禁止任何人更改window.undefined值,从而破坏基于该变量的代码。如果使用“usestrict”,任何试图更改其值的行为都将以错误告终,否则将被忽略。
其他回答
与void 0进行比较,以获得简洁性。
if (foo !== void 0)
它不像(typeoffoo!=='undefined')那样冗长
“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。
我很惊讶我还没有看到这个建议,但它比使用typeof测试更具特异性。如果您需要知道对象属性是用undefined初始化的还是从未初始化过,请使用Object.getOwnPropertyDescriptor():
// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');
if (typeof descriptor === 'undefined') {
// was never initialized
} else if (typeof descriptor.value === 'undefined') {
if (descriptor.get || descriptor.set) {
// is an accessor property, defined via getter and setter
} else {
// is initialized with `undefined`
}
} else {
// is initialized with some other value
}
我使用if(this.variable)来测试它是否被定义。一个简单的if(变量),在前面的答案中推荐,对我来说失败了。
事实证明,只有当变量是某个对象obj.someField的字段时,它才能工作,以检查它是否在字典中定义。但我们可以使用this或window作为字典对象,因为任何变量都是当前窗口中的字段,正如我所理解的那样。因此,这里有一个测试:
如果(this.abc)警报(“已定义”);其他的警报(“未定义”);abc=“abc”;如果(this.abc)警报(“已定义”);其他的警报(“未定义”);
它首先检测到变量abc未定义,并在初始化后定义。
也可以使用代理。它可以处理嵌套调用,但需要额外检查一次:
function resolveUnknownProps(obj, resolveKey) {
const handler = {
get(target, key) {
if (
target[key] !== null &&
typeof target[key] === 'object'
) {
return resolveUnknownProps(target[key], resolveKey);
} else if (!target[key]) {
return resolveUnknownProps({ [resolveKey]: true }, resolveKey);
}
return target[key];
},
};
return new Proxy(obj, handler);
}
const user = {}
console.log(resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else); // { isUndefined: true }
因此,您将像这样使用它:
const { isUndefined } = resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else;
if (!isUndefined) {
// Do something
}