Array.prototype.findIndex()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 2015 年 9 月以来,该特性已在各大浏览器中可用。

findIndex() 方法的 Array 实例返回数组中满足提供的测试函数的第一个元素的索引。如果没有任何元素满足测试函数,则返回 -1。

另请参阅 find() 方法,该方法返回满足测试函数的第一个元素(而不是其索引)。

试一试

const array = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array.findIndex(isLargeNumber));
// Expected output: 3

语法

js
findIndex(callbackFn)
findIndex(callbackFn, thisArg)

参数

callbackFn

一个用于执行数组中每个元素的函数。它应返回一个真值以指示已找到匹配的元素,否则返回一个假值。该函数会接收以下参数:

element

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

index

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

array

调用 findIndex() 的数组。

thisArg 可选

在执行 callbackFn 时用作 this 的值。请参阅 迭代方法

返回值

数组中通过测试的第一个元素的索引。否则为 -1

描述

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

callbackFn 会为数组的每一个索引调用,而不仅仅是那些有赋值的索引。对于稀疏数组中的空槽,其行为与 undefined 相同。

findIndex() 方法是 通用的。它只期望 this 值具有 length 属性和整数键属性。

示例

查找数组中第一个质数的索引

以下示例返回数组中第一个质数的索引,如果没有质数则返回 -1

js
function isPrime(n) {
  if (n < 2) {
    return false;
  }
  if (n % 2 === 0) {
    return n === 2;
  }
  for (let factor = 3; factor * factor <= n; factor += 2) {
    if (n % factor === 0) {
      return false;
    }
  }
  return true;
}

console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7)

注意:isPrime() 实现仅用于演示。对于实际应用,您需要使用高度记忆化的算法,例如埃拉托斯特尼筛法,以避免重复计算。

使用 callbackFn 的第三个参数

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

js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const firstTrough = numbers
  .filter((num) => num > 0)
  .findIndex((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(firstTrough); // 1

在稀疏数组上使用 findIndex()

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

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

在非数组对象上调用 findIndex()

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

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

规范

规范
ECMAScript® 2026 语言规范
# sec-array.prototype.findindex

浏览器兼容性

另见