JS:使用find()属性未定义的句柄 [英] JS: Handle with find() property undefined

查看:186
本文介绍了JS:使用find()属性未定义的句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method which returns a value from an element in the array. Not all the elements have the property I want to return. I would like to do this function with one line using the method find(). I've tried this way to solve it:

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

但是不包含属性execs的元素将返回错误undefined.

But the elements which don't contain the property execs return an error of undefined.

要解决此问题,我必须将结果存储在局部变量中:

To solve it, I had to store the result in a local variable:

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

但是我想知道我是否缺少某些东西,并且只需一句话就可以实现此功能.

But I would like to know if I am missing something and this function can be achieved with one sentence.

推荐答案

您似乎有一个大致的想法,Array.prototype.find会在数组中搜索第一个元素,该元素在用作回调的参数时将具有回调返回真实值.如果未找到任何内容,则返回undefined.

You seem to have the general idea, Array.prototype.find will search the array for the first element which, when used as an argument of the callback, will have the callback return a truthy value. If nothing is found, it returns undefined.

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

Your code should work, but yes, one way to do it in one line (if you want) is to use:

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

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

If Array.prototype.find returns undefined, the first inner parenthetical expression will be evaluated to empty object, which can attempt (and fail) to access the .execs key without a TypeError, which will also evaluate to undefined, in which case the function returns empty array, which is what your code above does.

有人已经评论了该解决方案,哈哈,但是正如评论所说,将其保持为多行并没有错(这样更易读).

Someone commented this solution already, lol, but as the comments say, nothing wrong with keeping it multiline (more readable that way).

这篇关于JS:使用find()属性未定义的句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆