通过.findLast()和.findLastIndex()从头到尾搜索数组的方法

640 阅读1分钟

这篇博文介绍了Wenlu Wang和Daniel Rosenwasser的ECMAScript提案"Array find from last"


本博文的主题:数组和类型化数组的方法

在这篇博文中,我们探讨了数组的方法。但我们所学的一切也适用于类型化数组。

搜索数组

以下三种方法从头到尾搜索数组。

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

到目前为止,只有.indexOf() 有一个从头到尾搜索的版本。

> ['a', 'b', 'a'].lastIndexOf('a')
2

该提案为.find().findIndex() 引入了这样的版本。

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

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

简单的实现

下面的代码显示了.findLast().findLastIndex() 的简单实现(比实际实现的检查少)。

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;
}

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;
}

可用性

该提案提到了2个目前可用的polyfills

此外,Lodash和Ramda等库也提供了Arrays的操作findLastfindLastIndex