Array.prototype.findLastIndex()

Baseline 2022

Newly available

Since August 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Array 实例的 findLastIndex() 方法以相反的顺序迭代数组,并返回满足提供的测试函数的第一个元素的索引。如果没有元素满足测试函数,则返回-1。

¥The findLastIndex() method of Array instances iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

另请参见 findLast() 方法,该方法返回满足测试函数的最后一个元素的值(而不是其索引)。

¥See also the findLast() method, which returns the value of last element that satisfies the testing function (rather than its index).

Try it

语法

¥Syntax

js
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)

参数

¥Parameters

callbackFn

对数组中的每个元素执行的函数。它应该返回 truthy 值以指示已找到匹配元素,否则返回 falsy 值。使用以下参数调用该函数:

element

数组中当前正在处理的元素。

index

数组中当前正在处理的元素的索引。

array

调用了数组 findLastIndex()

thisArg Optional

执行 callbackFn 时用作 this 的值。参见 迭代法

返回值

¥Return value

数组中通过测试的最后一个(最高索引)元素的索引。否则,如果未找到匹配元素,则为 -1

¥The index of the last (highest-index) element in the array that passes the test. Otherwise -1 if no matching element is found.

描述

¥Description

findLastIndex() 方法是 迭代法 方法。它按降序索引顺序为数组中的每个元素调用一次提供的 callbackFn 函数,直到 callbackFn 返回 truthy 值。然后 findLastIndex() 返回该元素的索引并停止遍历数组。如果 callbackFn 从未返回真值,则 findLastIndex() 返回 -1。请阅读 迭代法 部分,了解有关这些方法一般如何工作的更多信息。

¥The findLastIndex() method is an iterative method. It calls a provided callbackFn function once for each element in an array in descending-index order, until callbackFn returns a truthy value. findLastIndex() then returns the index of that element and stops iterating through the array. If callbackFn never returns a truthy value, findLastIndex() returns -1. Read the iterative methods section for more information about how these methods work in general.

callbackFn 会针对数组的每个索引调用,而不仅仅是那些已分配值的索引。稀疏数组 中的空插槽的行为与 undefined 相同。

¥callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.

findLastIndex() 方法是 generic。它只期望 this 值具有 length 属性和整数键控属性。

¥The findLastIndex() method is generic. It only expects the this value to have a length property and integer-keyed properties.

示例

¥Examples

查找数组中最后一个素数的索引

¥Find the index of the last prime number in an array

以下示例返回数组中最后一个素数元素的索引,如果没有素数则返回 -1

¥The following example returns the index of the last element in the array that is a prime number, or -1 if there is no prime number.

js
function isPrime(element) {
  if (element % 2 === 0 || element < 2) {
    return false;
  }
  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
    if (element % factor === 0) {
      return false;
    }
  }
  return true;
}

console.log([4, 6, 8, 12].findLastIndex(isPrime)); // -1, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLastIndex(isPrime)); // 5

使用 callbackFn 的第三个参数

¥Using the third argument of callbackFn

如果你想访问数组中的另一个元素,特别是当你没有引用该数组的现有变量时,array 参数非常有用。以下示例首先使用 filter() 提取正值,然后使用 findLastIndex() 查找小于其邻居的最后一个元素。

¥The array argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses filter() to extract the positive values and then uses findLastIndex() to find the last element that is less than its neighbors.

js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const lastTrough = numbers
  .filter((num) => num > 0)
  .findLastIndex((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && num >= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
    return true;
  });
console.log(lastTrough); // 6

在稀疏数组上使用 findLastIndex()

¥Using findLastIndex() on sparse arrays

你可以在稀疏数组中搜索 undefined 并获取空槽的索引。

¥You can search for undefined in a sparse array and get the index of an empty slot.

js
console.log([1, , 3].findLastIndex((x) => x === undefined)); // 1

对非数组对象调用 findLastIndex()

¥Calling findLastIndex() on non-array objects

findLastIndex() 方法读取 thislength 属性,然后访问键为小于 length 的非负整数的每个属性。

¥The findLastIndex() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

js
const arrayLike = {
  length: 3,
  0: 2,
  1: 7.3,
  2: 4,
  3: 3, // ignored by findLastIndex() since length is 3
};
console.log(
  Array.prototype.findLastIndex.call(arrayLike, (x) => Number.isInteger(x)),
); // 2

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.findlastindex

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看