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

摘要:今天来看一个 ECMAScript 提案:findLast() 和 findLastIndex()。提案原因:在 JavaScript 中,可以通过 find() 和 findIndex() 查找数组中的值。不过,这些方法从数组的开始进行遍历

查找数组元素

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

方法一:

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

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_11785