我的 IVR 应用程序以 JS 对象和数组的形式接收业务数据。例如,我们的一位客户的姓名被访问如下:
customerData.customerList[customerIndex].customerName
现在,在某些情况下,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
。之后,您可以跳过对 undefined 的测试,直到您希望的任何级别
((customerData || {}).customerList || [])[customerIndex] !== undefined
关于JavaScript:检查对象字段是否未定义而不检查对象是否未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5835895/