JavaScript:检查对象字段是否未定义,而不检查对象是否未定义

IVR*_*ger 3 javascript types typeof

我的IVR应用程序以JS对象和数组的形式接收业务数据.例如,我们的客户名称访问如下:

customerData.customerList[customerIndex].customerName
Run Code Online (Sandbox Code Playgroud)

现在,在某些情况下,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
}
Run Code Online (Sandbox Code Playgroud)

是否有更简单(更清洁?)的方法来实现这一点,而无需检查对象上的每个字段?

谢谢.

Imr*_*ran 6

您需要编写第一个typeof以确保customerData已声明.之后,您可以跳过未定义的测试,直到您希望的任何级别

((customerData || {}).customerList || [])[customerIndex] !== undefined
Run Code Online (Sandbox Code Playgroud)