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

瀏覽器相容性

另見