Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. Array
  6. Array.prototype.findIndex()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

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() 方法,它返回满足测试函数的第一个元素(而不是它的索引)。

尝试一下

const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.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() 不会改变被调用的数组,但是提供给callbackFn 的函数可能会改变它。但需要注意的是,在第一次调用callbackFn之前,数组的长度会被保存。因此:

  • 当调用findIndex() 时,callbackFn 不会访问超出数组初始长度的任何元素。
  • 对已经访问过的索引的更改不会导致再次在这些元素上调用callbackFn
  • 如果callbackFn 改变了数组中已存在但尚未被访问的元素,则传递给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,没有找到console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2(array[2] 是 7)

备注:isPrime() 实现仅供演示。在实际应用中,为了避免重复计算,会使用大量记忆化的算法,例如埃拉托斯特尼筛法

在稀疏数组上使用 findIndex()

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

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

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

findIndex() 方法读取thislength 属性,并访问每个整数索引。

js
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

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp