简体   繁体   English

如何检查对象是否存在并具有X属性?

[英]How can I check if an object exists and has X property?

I am trying to check if an object exists and has X property. 我正在尝试检查对象是否存在并具有X属性。

First I try it like this: 首先,我尝试这样:

let object = {
    foo: 1
}

console.log('foo' in object)
console.log(object.hasOwnProperty('foo'))
console.log(typeof(object.foo) !== undefined)

But I realized that if the object is undefined all of them return errors. 但是我意识到,如果对象是未定义的,那么它们都将返回错误。

I know I can use: 我知道我可以使用:

let object = undefined

if (object) {
    console.log('foo' in object)
    console.log(object.hasOwnProperty('foo'))
    console.log(typeof (object.foo) !== undefined)
}

To check if an object exists and has X property, but I would like to know if I can resume all of this in one line. 要检查一个对象是否存在并具有X属性,但是我想知道是否可以在一行中恢复所有这些。 Something like: 就像是:

typeof(object) !== undefined && ('foo' in object)

You can use it just like you were doing in your multi line example, by just testing object . 您可以像测试多行示例一样使用它,只需测试object

 function testObject(object) { if (object && ('foo' in object)) { console.log(true); } else { console.log(false); } } testObject(undefined); testObject({foo: 'bar'}); 

只需首先使用检查对象是否存在:

object && 'foo' in object

these examples works fine: 这些示例工作正常:

 let object = { foo: 1 }; if (object && object.hasOwnProperty('foo')) { console.log(object['foo']); } else { console.log('object has no foo key'); } let obj2 = {}; if (obj2 && obj2.hasOwnProperty('foo')) { console.log(obj2['foo']); } else { console.log('obj2 has no foo key'); } let obj3; if (obj3 && obj3.hasOwnProperty('foo')) { console.log(obj2['foo']); } else { console.log('obj3 has no foo key'); } 

For this one I don't have any idea 对于这个我没有任何想法

 if (obj3 && obj3.hasOwnProperty('foo')) { console.log(obj2['foo']); } else { console.log('obj3 has no foo key'); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM