【问题标题】:JavaScript: Checking if an object field is undefined without checking if the object is undefinedJavaScript:检查对象字段是否未定义而不检查对象是否未定义
【发布时间】:2011-08-15 16:57:52
【问题描述】:

我的 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
}

有没有更简单(更干净?)的方法来完成此操作,而无需检查对象上的每个字段?

谢谢。

【问题讨论】:

    标签: javascript types typeof


    【解决方案1】:

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

    ((customerData || {}).customerList || [])[customerIndex] !== undefined
    

    【讨论】:

    • 如果customerData 尚未用var 声明,您仍然需要typeof 检查。
    • 你是对的,但之后可以避免使用逻辑或对undefined 进行任何级别的测试
    • 你的方法很聪明,它让我想起了我曾经在遍历 Web 服务返回的 XML 文档时使用的方法 :-) +1。
    【解决方案2】:

    我知道这行得通,但我敢猜测会有一些反对意见......我很想听听:

    var customerName = function(){
       try{ return customerData.customerList[customerIndex].customerName; }
       catch(e){ return null; }
    };
    if (customerName) {
       ...
    }
    

    【讨论】:

    猜你喜欢
    • 2017-08-02
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    相关资源
    最近更新 更多