最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

types - JavaScript: Checking if an object field is undefined without checking if the object is undefined - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

You 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) {
   ...
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论