JS:处理 find() 属性未定义

Joa*_*oan 5 javascript find typescript ecmascript-2017

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

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

但是不包含该属性的元素execs返回undefined.

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

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

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

小智 9

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

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

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

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

编辑:有人已经评论了这个解决方案,哈哈,但正如评论所说,保持多行没有错(这样更易读)。


fed*_*ghe -1

关于什么

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

...

编辑

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 : [];
}
Run Code Online (Sandbox Code Playgroud)

这次至少我跑了几次

  • 答案是错误的... `[{id:'foo', execs:[]}].find(el => 'execs' in el && el.id == 'bar' ).execs` 它仍然在进行抛出同样的错误。 (2认同)