admin 管理员组文章数量: 1087134
My IVR app receives business data in the form of JS objects and arrays. For example, the name of one of our customers is accessed as follows:
customerData.customerList[customerIndex].customerName
Now, in some cases, customerName is undefined, because the entire object is undefined. Right now, in order to catch that, I have some nested logic that checks each level for being undefined, before finally checking the last:
if (typeof customerData != 'undefined' &&
typeof customerData.customerList &&
typeof customerData.customerList[customerIndex] != 'undefined' &&
typeof customerData.customerList[customerIndex].customerName != 'undefined')
{
//do something awesome with customer name, here
}
Is there an easier (cleaner?) way to acplish this, without having to check each field on the object?
Thanks.
My IVR app receives business data in the form of JS objects and arrays. For example, the name of one of our customers is accessed as follows:
customerData.customerList[customerIndex].customerName
Now, in some cases, customerName is undefined, because the entire object is undefined. Right now, in order to catch that, I have some nested logic that checks each level for being undefined, before finally checking the last:
if (typeof customerData != 'undefined' &&
typeof customerData.customerList &&
typeof customerData.customerList[customerIndex] != 'undefined' &&
typeof customerData.customerList[customerIndex].customerName != 'undefined')
{
//do something awesome with customer name, here
}
Is there an easier (cleaner?) way to acplish this, without having to check each field on the object?
Thanks.
Share Improve this question edited Apr 29, 2011 at 18:35 Alex K. 176k32 gold badges274 silver badges296 bronze badges asked Apr 29, 2011 at 18:30 IVR AvengerIVR Avenger 15.5k13 gold badges49 silver badges60 bronze badges2 Answers
Reset to default 6You need to write the first typeof to ensure that customerData
has been declared. After that, you can skip testing for undefined upto any level you wish
((customerData || {}).customerList || [])[customerIndex] !== undefined
I know this works, but would venture to guess there will be some objections... which I'd love to hear:
var customerName = function(){
try{ return customerData.customerList[customerIndex].customerName; }
catch(e){ return null; }
};
if (customerName) {
...
}
本文标签:
版权声明:本文标题:types - JavaScript: Checking if an object field is undefined without checking if the object is undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744060728a2526669.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论