如何检查对象中是否存在对象 [英] How to check if object within object exists
问题描述
似乎以下用于检查对象成员是否存在的技术会产生错误,因为在检查之前尚未声明'bar'父对象,这意味着我必须在检查之前声明它或使用两个'typeof'表达式,其中任何一个都是超额代码:
It seems that the following technique for checking the existence of an object member produces an error because the 'bar' parent object hasn't been declared before the check, which means I either have to declare it before the check or use two 'typeof' expressions, either of which would be excess code:
var foo = {},
newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );
Error: foo.bar is undefined
那么,你如何检查如果未声明的对象中的成员存在而没有产生错误?
So, how do you check if a member within an undeclared object exists without producing an error?
我喜欢javascript,但有时......
I love javascript, but sometimes...
推荐答案
只需使用以下代码即可:
It can be done simply using the code below:
var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal
属性为null或未定义,它将是评估为false,因此上述代码只会处理第一个'false'语句。
A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.
这篇关于如何检查对象中是否存在对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!