A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf below:

Array.prototype.indexOf() - JavaScript | MDN

Array.prototype.indexOf()

Baseline Widely available

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
構文
indexOf(searchElement)
indexOf(searchElement, fromIndex)
引数
searchElement

検索する配列要素です。

fromIndex 省略可

検索し始める位置のゼロから始まるインデックスで、整数に変換されます。

返値

配列内にある最初の searchElement のインデックスです。見つからなかった場合は `-1`` です。

解説

indexOf() メソッドは searchElement と配列の要素を厳密等価(三重イコール演算子 === で使われるのと同じ方法)を使って比較します。 NaN の値は等しい値として比較されることはないので、indexOf() は searchElement が NaN のときには常に -1 を返します。

indexOf() メソッドは疎配列の空スロットをスキップします。

indexOf() メソッドは汎用的です。これは this 値に length プロパティと整数キーのプロパティがあることだけを期待します。

例 indexOf() の使用

以下の例は indexOf() を使って、配列中のある値の位置を探しています。

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 を検索することはできません。

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,spinach
updateVegetablesCollection(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));
// 0
console.log(Array.prototype.indexOf.call(arrayLike, 5));
// -1
仕様書 ブラウザーの互換性 関連情報

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4