4

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

 2 years ago
source link: https://www.fly63.com/article/detial/11785
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-06-24阅读量: 7标签: 数组分享

扫一扫分享

查找数组元素

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

['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://www.fly63.com/article/detial/11785


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK