【问题标题】:JS: Handle with find() property undefinedJS:使用 find() 属性未定义的句柄
【发布时间】:2019-02-22 16:16:09
【问题描述】:

我有一个从数组中的元素返回值的方法。并非所有元素都具有我想要返回的属性。我想用find() 的方法用一行来完成这个功能。我试过这种方法来解决它:

getExecsFromTour(tourId){
 return this.repInfo.find(el => el.id == tourId ).execs || [];
}

但不包含属性execs 的元素返回undefined 错误。

为了解决这个问题,我不得不将结果存储在一个局部变量中:

getExecsFromTour(tourId){
    let items       = this.repInfo.find(el => el.id == tourId);
    return items    != undefined ? items.execs : [];
}

但我想知道我是否遗漏了什么,这个功能可以用一句话来实现。

【问题讨论】:

  • 如果你真的需要这个是一行,你可以使用(this.repInfo.find(el => el.id == tourId) || {}).execs || [];
  • 让内容多行可读并没有什么坏处......
  • 您好!谢谢@Titus,我完全忘记了{}statment >.

标签: javascript typescript find ecmascript-2017


【解决方案1】:

怎么样

getExecsFromTour(tourId){
     return this.repInfo.find(el => 'execs' in el && el.id == tourId ).execs || [];
}

...

已编辑

var a = [{execs : 1, id:4}, {id:5}];
function getExecsFromTour(tourId, x){
    return (x = a.find(el => 'execs' in el && el.id == tourId )) ? x.execs : [];
}

这次至少我跑了几次

【讨论】:

  • 我不反对,但如果你愿意,我可以再给你一个。
  • 答案是错误的....[{id:'foo', execs:[]}].find(el => 'execs' in el && el.id == 'bar' ).execs 还是会抛出同样的错误。
【解决方案2】:

您似乎有一般的想法,Array.prototype.find 将在数组中搜索第一个元素,当用作回调的参数时,回调将返回一个真实值。如果没有找到,则返回undefined

您的代码应该可以工作,但是,在一行中执行此操作的一种方法(如果您愿意)是使用:

getExecsFromTour(tourId){
  return (this.repInfo.find(el => el.id == tourId) || {}).execs || [];
}

如果Array.prototype.find 返回undefined,第一个内括号表达式将被评估为空对象,它可以尝试(并且失败)在没有TypeError 的情况下访问.execs 键,这也将评估为@ 987654328@,在这种情况下,函数返回空数组,这就是你上面的代码所做的。

编辑:已经有人评论了这个解决方案,大声笑,但正如 cmets 所说,保持多行并没有错(这样更具可读性)。

【讨论】:

  • 您好!是的,之前有人回答过这个问题,但没有人解释过。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
  • 2021-08-28
相关资源
最近更新 更多