JavaScript 有数组方法,如 indexOf
和 find
用于获取数组中符合条件的第一个元素。 indexOf
的对应项是 lastIndexOf
,它从数组末尾开始搜索。我现在想知道是否有从数组末尾开始的 find
的对应项,例如 Ramda's findLast
的 native 实现.
由于性能成本,我宁愿不使用 array.slice().reverse().find()
也不想使用 for
循环,因为它很冗长而不是本着函数式编程的精神
最佳答案
您可以使用reduceRight
,这符合函数式编程的精神。但是,在找到匹配项后提前返回并不像在 for
循环中那样容易 ( but possible):
const lastIndexOf = (needle, haystack) =>
haystack.reduceRight((a, e, i) =>
a >= 0 ? a : e === needle ? i : -1
, -1)
;
const arr = [1,4,3,5,5,4,5];
console.log(lastIndexOf(4, arr));
console.log(lastIndexOf(2, arr));
还有递归,它有类似的效率问题(堆栈帧开销,没有瞬时提前返回,必须编写一个帮助程序或额外的条件,如果数组很大,你会破坏堆栈......):
const lastIndexOf = (needle, haystack, idx) =>
lastIndexOfHelper(needle, haystack, haystack.length - 1)
;
const lastIndexOfHelper = (needle, haystack, idx) =>
idx < 0 || haystack[idx] === needle ?
idx : lastIndexOfHelper(needle, haystack, idx - 1)
;
const arr = [1,4,3,5,5,4,5];
console.log(lastIndexOf(4, arr));
console.log(lastIndexOf(2, arr));
关于javascript - 如何找到从数组末尾开始的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52558924/