JavaScript:检查对象字段是否未定义而未检查对象是否未定义
问题描述:
我的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
}
有没有做到这一点更容易(清洁?)的方式,而不必检查对象上的每个字段?
谢谢。
答
您需要编写第一个typeof以确保customerData
已被声明。在此之后,你可以跳过测试未定义高达任何级别您希望
((customerData || {}).customerList || [])[customerIndex] !== undefined
答
我知道这个作品,但冒昧猜测会有一些反对意见......我很想听听:
var customerName = function(){
try{ return customerData.customerList[customerIndex].customerName; }
catch(e){ return null; }
};
if (customerName) {
...
}
+0
Try-catch块对于浏览器难以优化。要了解更多:https://github.com/petkaantonov/bluebird/wiki/Optimization-killers – Venar303 2015-03-09 19:59:34
如果还没有用'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