JavaScript 数组新方法:findLast() 与 findLastIndex() 详解

作者:代码拾荒时间:2026-10-25 08:48:06浏览:377

本文介绍 ECMAScript 提案中的 findLast() 和 findLastIndex() 方法,它们允许从数组末尾向前遍历查找元素。相比先反转数组再使用 find,这两个新 API 语义更清晰且无需额外操作。文章包含基本用法、简单实现及 Lodash 源码解析,并指出 Safari 15.4 已支持该特性。

本文介绍 ECMAScript 提案中新增的 findLast() 和 findLastIndex() 方法。

提案背景

在 JavaScript 中,开发者通常使用 find() 和 findIndex() 来查找数组中的值。然而,这两个方法默认从数组头部开始遍历:

const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}];

array.find(elem => elem.v > 3); // {v: 4}
array.findIndex(elem => elem.v > 3); // 3

若需从数组尾部开始查找,传统做法是先反转数组,再调用上述方法。这引入了额外的数组操作开销。

基本用法

Wenlu Wang 和 Daniel Rosenwasser 提出的 ECMAScript 提案解决了这一问题,其核心优势在于语义的明确性。

这两个方法的调用方式与 find()、findIndex() 类似,区别在于它们从后向前遍历数组,且适用于数组和类数组对象。

  • findLast() 返回第一个匹配的元素,若未找到则返回 undefined;
  • findLastIndex() 返回第一个匹配元素的索引,若未找到则返回 -1;
const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}];

array.findLast(elem => elem.v > 3); // {v: 5}
array.findLastIndex(elem => elem.v > 3); // 4
array.findLastIndex(elem => elem.v > 5); // -1

简单实现

下面展示这两个方法的简易实现逻辑。

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

const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}];
findLast(array, elem => elem.v > 3, array) // {v: 5}
findLast(array, elem => elem.v > 5, array) // -1
  • 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;
}

const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}];
findLastIndex(array, elem => elem.v > 3, array) // 4
findLastIndex(array, elem => elem.v > 5, array) // -1

Lodash 源码分析

以下是 Lodash 库中实现这两个方法的源码,供开发者参考学习:

  • findLast()
import findLastIndex from './findLastIndex.js'
import isArrayLike from './isArrayLike.js'

/**
 * This method is like `find` except that it iterates over elements of
 * `collection` from right to left.
 *
 * @since 2.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} [fromIndex=collection.length-1] The index to search from.
 * @returns {*} Returns the matched element, else `undefined`.
 * @see find, findIndex, findKey, findLastIndex, findLastKey
 * @example
 *
 * findLast([1, 2, 3, 4], n => n % 2 == 1)
 * // => 3
 */
function findLast(collection, predicate, fromIndex) {
  let iteratee
  const iterable = Object(collection)
  if (!isArrayLike(collection)) {
    collection = Object.keys(collection)
    iteratee = predicate
    predicate = (key) => iteratee(iterable[key], key, iterable)
  }
  const index = findLastIndex(collection, predicate, fromIndex)
  return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined
}

export default findLast
  • findLastIndex()
import baseFindIndex from './.internal/baseFindIndex.js'
import toInteger from './toInteger.js'

/**
 * This method is like `findIndex` except that it iterates over elements
 * of `collection` from right to left.
 *
 * @since 2.0.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} [fromIndex=array.length-1] The index to search from.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @see find, findIndex, findKey, findLast, findLastKey
 * @example
 *
 * const users = [
 *   { 'user': 'barney',  'active': true },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': false }
 * ]
 *
 * findLastIndex(users, ({ user }) => user == 'pebbles')
 * // => 2
 */
function findLastIndex(array, predicate, fromIndex) {
  const length = array == null ? 0 : array.length
  if (!length) {
    return -1
  }
  let index = length - 1
  if (fromIndex !== undefined) {
    index = toInteger(fromIndex)
    index = fromIndex < 0
      ? Math.max(length + index, 0)
      : Math.min(index, length - 1)
  }
  return baseFindIndex(array, predicate, index, true)
}

export default findLastIndex

浏览器支持情况

该提案目前处于第 3 阶段,提案地址为:https://github.com/tc39/proposal-array-find-from-last

此外,Lodash 和 Ramda 等第三方库已为数组提供了 findLast() 和 findLastIndex() 操作支持。

目前,Safari 15.4 已原生支持这两个方法。期待更多主流浏览器跟进支持。

总结

本文介绍了 JavaScript 新功能 findLast() 和 findLastIndex() 的用法与实现。如需了解更多 JS findLast() 和 findLastIndex() 相关内容,请搜索本站历史文章或浏览后续相关文章,感谢支持!

作者最新文章