关于javascript:ECMAScript-新提案findLast和findLastIndex从尾到头搜索数组

8次阅读

共计 1287 个字符,预计需要花费 4 分钟才能阅读完成。

作者: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 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。

正文完
 0