此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Array.prototype.findIndex()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年9月.
findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。
另请参阅find() 方法,它返回满足测试函数的第一个元素(而不是它的索引)。
In this article
尝试一下
const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.findIndex(isLargeNumber));// Expected output: 3语法
findIndex(callbackFn)findIndex(callbackFn, thisArg)参数
返回值
数组中第一个满足测试条件的元素的索引。否则返回-1。
描述
findIndex() 是一种迭代方法。它按照索引升序依次遍历数组中的每个元素,并调用提供的callbackFn 函数,直到callbackFn 返回一个真值。然后findIndex() 返回该元素的索引并停止遍历数组。如果callbackFn 从未返回一个真值,则findIndex() 返回-1。
callbackFn 被调用来处理数组的每一个索引,而不仅仅是那些有值的索引。在稀疏数组中,未赋值的空槽与undefined 表现相同。
findIndex() 不会改变被调用的数组,但是提供给callbackFn 的函数可能会改变它。但需要注意的是,在第一次调用callbackFn之前,数组的长度会被保存。因此:
- 当调用
findIndex()时,callbackFn不会访问超出数组初始长度的任何元素。 - 对已经访问过的索引的更改不会导致再次在这些元素上调用
callbackFn。 - 如果
callbackFn改变了数组中已存在但尚未被访问的元素,则传递给callbackFn的该元素的值将是该元素在被访问时的值。被删除的元素被视为undefined。
警告:上述类型的并发修改经常导致难以理解的代码,通常应避免(特殊情况除外)。
findIndex() 方法是通用的。它只期望this 值具有length 属性和整数键属性。
示例
>寻找数组中的首个素数的索引
以下示例返回数组中第一个素数的索引,如果没有素数则返回-1。
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,没有找到console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2(array[2] 是 7)备注:isPrime() 实现仅供演示。在实际应用中,为了避免重复计算,会使用大量记忆化的算法,例如埃拉托斯特尼筛法。
在稀疏数组上使用 findIndex()
你可以搜索稀疏数组中的undefined 并来获取空槽的索引。
console.log([1, , 3].findIndex((x) => x === undefined)); // 1在非数组对象上调用 findIndex()
findIndex() 方法读取this 的length 属性,并访问每个整数索引。
const arrayLike = { length: 3, 0: 2, 1: 7.3, 2: 4,};console.log( Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)),); // 1规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.findindex> |