我的IVR应用程序以JS对象和数组的形式接收业务数据。JavaScript:检查对象字段是否未定义而未检查对象是否未定义
customerData.customerList[customerIndex].customerName
现在,在某些情况下,客户名称是不确定的,因为整个对象是不确定的:例如,如下我们的一个客户的名字被访问。眼下,为了赶上这一点,我有一个检查被不确定的每个级别一些的嵌套逻辑,最后检查前最后:
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
}
有没有做到这一点更容易(清洁?)的方式,而不必检查对象上的每个字段?
谢谢。
如果还没有用'var'声明''customerData',你仍然需要'typeof'检查。 – 2011-04-29 18:37:34
你是对的,但之后可以避免测试'undefined'到逻辑的任何级别 - 或者 – Imran 2011-04-29 18:40:27
你的方法很聪明,它让我想起了我曾经在遍历由Web服务返回的XML文档时使用的一种方法:-) +1。 – 2011-04-29 18:42:14