このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
Array.prototype.indexOf()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
indexOf() はArray インスタンスのメソッドで、引数に与えられた内容と同じ内容を持つ最初の配列要素の添字を返します。存在しない場合は -1 を返します。
In this article
試してみましょう
const beasts = ["ant", "bison", "camel", "duck", "bison"];console.log(beasts.indexOf("bison"));// 予想される結果: 1// Start from index 2console.log(beasts.indexOf("bison", 2));// 予想される結果: 4console.log(beasts.indexOf("giraffe"));// 予想される結果: -1構文
indexOf(searchElement)indexOf(searchElement, fromIndex)引数
searchElement検索する配列要素です。
fromIndex省略可検索し始める位置のゼロから始まるインデックスで、整数に変換されます。
- インデックスが負の場合、配列の末尾からさかのぼって数えます。
-array.length <= fromIndex < 0の場合、fromIndex + array.lengthが使用されます。ただし、この場合でも配列は前から後ろに向けて検索されます。 fromIndex < -array.lengthまたはfromIndexが省略された場合は0が使用され、配列全体に対して検索が行われます。fromIndex >= array.lengthの場合、配列の検索は行われず、falseが返されます。
- インデックスが負の場合、配列の末尾からさかのぼって数えます。
返値
配列内にある最初のsearchElement のインデックスです。見つからなかった場合は `-1`` です。
解説
indexOf() メソッドはsearchElement と配列の要素を厳密等価(三重イコール演算子=== で使われるのと同じ方法)を使って比較します。NaN の値は等しい値として比較されることはないので、indexOf() はsearchElement がNaN のときには常に-1 を返します。
indexOf() メソッドは疎配列の空スロットをスキップします。
indexOf() メソッドは汎用的です。これはthis 値にlength プロパティと整数キーのプロパティがあることだけを期待します。
例
>indexOf() の使用
以下の例はindexOf() を使って、配列中のある値の位置を探しています。
const array = [2, 9, 9];array.indexOf(2); // 0array.indexOf(7); // -1array.indexOf(9, 2); // 2array.indexOf(2, -1); // -1array.indexOf(2, -3); // 0indexOf() を使ってNaN を検索することはできません。
const array = [NaN];array.indexOf(NaN); // -1ある要素の存在をすべて見つける
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]要素が配列内に存在するかどうかを調べ、配列を更新する
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,spinachupdateVegetablesCollection(veggies, "spinach");// spinach already exists in the veggies collection.疎配列での indexOf() の使用
疎配列の空のスロットを検索するためにindexOf() を使用することはできません。
console.log([1, , 3].indexOf(undefined)); // -1配列ではないオブジェクトに対する indexOf() の呼び出し
indexOf() メソッドはthis のlength プロパティを読み込み、次にキーがlength より小さい非負の整数である各プロパティにアクセスします。
const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // length が 3 であるため indexOf() から無視される};console.log(Array.prototype.indexOf.call(arrayLike, 2));// 0console.log(Array.prototype.indexOf.call(arrayLike, 5));// -1仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.indexof> |