Array.prototype.indexOf()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

indexOf() 方法用於在 Array 例項中查詢給定元素的第一個索引,如果未找到,則返回 -1。

試一試

const beasts = ["ant", "bison", "camel", "duck", "bison"];

console.log(beasts.indexOf("bison"));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf("bison", 2));
// Expected output: 4

console.log(beasts.indexOf("giraffe"));
// Expected output: -1

語法

js
indexOf(searchElement)
indexOf(searchElement, fromIndex)

引數

searchElement

要在陣列中定位的元素。

fromIndex 可選

開始搜尋的基於零的索引,轉換為整數

  • 負數索引從陣列末尾開始計數 — 如果 -array.length <= fromIndex < 0,則使用 fromIndex + array.length。請注意,在這種情況下,陣列仍然從前向後搜尋。
  • 如果 fromIndex < -array.length 或省略了 fromIndex,則使用 0,這將導致搜尋整個陣列。
  • 如果 fromIndex >= array.length,則不搜尋陣列並返回 -1

返回值

陣列中 searchElement 的第一個索引;如果未找到,則為 -1

描述

indexOf() 方法使用嚴格相等(與 === 運算子使用的演算法相同)比較 searchElement 與陣列中的元素。NaN 值永遠不相等,因此當 searchElementNaN 時,indexOf() 始終返回 -1

indexOf() 方法會跳過稀疏陣列中的空槽。

indexOf() 方法是通用的。它只期望 this 值具有 length 屬性和整數鍵屬性。

示例

使用 indexOf()

以下示例使用 indexOf() 在陣列中查詢值。

js
const array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

您不能使用 indexOf() 搜尋 NaN

js
const array = [NaN];
array.indexOf(NaN); // -1

查詢元素的所有出現次數

js
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

查詢元素是否存在於陣列中,以及更新陣列

js
function updateVegetablesCollection(veggies, veggie) {
  if (veggies.indexOf(veggie) === -1) {
    veggies.push(veggie);
    console.log(`New veggies collection is: ${veggies}`);
  } else {
    console.log(`${veggie} already exists in the veggies collection.`);
  }
}

const veggies = ["potato", "tomato", "chillies", "green-pepper"];

updateVegetablesCollection(veggies, "spinach");
// New veggies collection is: potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, "spinach");
// spinach already exists in the veggies collection.

在稀疏陣列上使用 indexOf()

您不能使用 indexOf() 搜尋稀疏陣列中的空槽。

js
console.log([1, , 3].indexOf(undefined)); // -1

在非陣列物件上呼叫 indexOf()

indexOf() 方法讀取 thislength 屬性,然後訪問鍵為小於 length 的非負整數的每個屬性。

js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 5, // ignored by indexOf() since length is 3
};
console.log(Array.prototype.indexOf.call(arrayLike, 2));
// 0
console.log(Array.prototype.indexOf.call(arrayLike, 5));
// -1

規範

規範
ECMAScript® 2026 語言規範
# sec-array.prototype.indexof

瀏覽器相容性

另見