【问题标题】:Ensure es6 find don't break when property is not defined [duplicate]确保未定义属性时 es6 find 不会中断 [重复]
【发布时间】:2019-10-04 15:16:21
【问题描述】:

我有这个代码

const arr = [{
  id: 1,
  name: 'anything'
}, {
  id: 2,
  name: 'something'
}]

const target = [1]

我要查找target是否为1,我要name属性值

我会的

arr.find(o => target.includes(o.id)).name

但如果

arr.find(o => target.includes(o.id)) 没有name 属性,它会破坏整个应用程序并引发错误。

那么如何确保它不会崩溃呢?我可以这样做,但它很难看

const somethingValue = arr.find(o => target.includes(o.id)) && arr.find(o => target.includes(o.id)).name

或者我必须映射以确保 arr 始终具有 name 属性,如果 arr 是动态的并且南方来自外部方,我必须这样做。

还有什么办法可以解决吗?

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    您可以使用空对象{}|| 运算符。

    (arr.find(o => target.includes(o.id)) || {}).name
    

    如果find() 将返回undefined,则表达式将评估为{} 并尝试从{} 获取name,即undefined

    【讨论】:

      【解决方案2】:

      先将.find的结果提取到一个变量中,然后检查该变量是否被定义:

      const foundObject = arr.find(o => target.includes(o.id));
      const somethingValue = foundObject ? foundObject.name : null;
      

      【讨论】:

      • 是的,我知道,但这是一个两步的事情
      • 不要害怕定义变量——没有必要为了提取不存在的属性而创建额外的对象
      猜你喜欢
      • 2018-10-28
      • 2019-07-20
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      相关资源
      最近更新 更多