【发布时间】: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