ECMAScript 提案:.findLast()和.findLastIndex()从尾到头搜索数组
查找数组元素
下面有三种方法从头到尾查找数组元素。
方法一:
['a', 'b', 'a'].indexOf('a') // 0
['a', 'b', 'a'].indexOf('c') // -1方法二:
['a1', 'b', 'a2'].find(x => x.startsWith('a')) // 'a1'
['a1', 'b', 'a2'].find(x => x.startsWith('c')) // undefined方法三:
['a1', 'b', 'a2'].findIndex(x => x.startsWith('a')) // 0
['a1', 'b', 'a2'].findIndex(x => x.startsWith('c')) // -1最新提案引入了 findLast 和 findIndex 方法,用法如下:
['a1', 'b', 'a2'].findLast(x => x.startsWith('a')) // 'a2'
['a1', 'b', 'a2'].findLastIndex(x => x.startsWith('a')) // 2简单的实现方式
下面,我们简单来实现一下.findLast()和.findLastIndex():
.findLast()
function findLast(arr, callback, thisArg) {
for (let index = arr.length-1; index >= 0; index--) {
const value = arr[index];
if (callback.call(thisArg, value, index, arr)) {
return value;
}
}
return undefined;
}.findLastIndex()
function findLastIndex(arr, callback, thisArg) {
for (let index = arr.length-1; index >= 0; index--) {
const value = arr[index];
if (callback.call(thisArg, value, index, arr)) {
return index;
}
}
return -1;
}polyfill
如果你想先提前体验,可以在 core-js 中引入。
地址:https://github.com/tc39/proposal-array-find-from-last#polyfill
来源:https://2aliy.com/2022/03/array-find-last.html
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!