【问题标题】:Only returning value if .includes() finds something using .find()仅当 .includes() 使用 .find() 找到某些内容时才返回值
【发布时间】:2022-01-20 23:23:39
【问题描述】:

我设置了这个函数,使用 Google Maps API 响应:

 zipCode: addressObject.address_components.find((component) =>
          component.types.includes("postal_code")
        ).long_name,

但是,postal_code 不在types 中,那么当types 数组包含postal_code 时,如何只检索long_name

【问题讨论】:

    标签: javascript arrays object ecmascript-6


    【解决方案1】:

    在没有找到项目时使用optional chaining (?.) 运算符获取undefined

    zipCode: addressObject.address_components.find((component) =>
      component.types.includes("postal_code")
    )?.long_name,
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-02
      • 2021-11-16
      • 2010-12-12
      • 1970-01-01
      相关资源
      最近更新 更多