likes
comments
collection
share

ECMAScript 提案:.findLast()和.findLastIndex()从尾到头搜索数组

作者站长头像
站长
· 阅读数 259
作者:knaagar译者:前端小智来源:dev

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。

查找数组元素

下面有三种方法从头到尾查找数组元素。

方法一:

['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

最新提案引入了 findLastfindIndex 方法,用法如下:

['a1', 'b', 'a2'].findLast(x => x.startsWith('a')) // 'a2'
['a1', 'b', 'a2'].findLastIndex(x => x.startsWith('a')) // 2

3.简单的实现方式

下面,我们简单来实现一下.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/propo...


代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

原文:https://2aliy.com/2022/03/arr...

交流

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。

ECMAScript 提案:.findLast()和.findLastIndex()从尾到头搜索数组