Array.prototype.entries()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

entries()Array インスタンスのメソッドで、配列内の各要素に対するキー/値のペアを含む新しい配列イテレーターオブジェクトを返します。

試してみましょう

構文

js
entries()

引数

なし。

返値

解説

疎配列で使用された場合、 entries() メソッドは空のスロットを undefined の値が設定されているかのように反復処理します。

entries() メソッドは汎用的です。このメソッドは this の値に length プロパティと整数のキーを持ったプロパティがあることだけを求めます。

インデックスと要素の反復処理

js
const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}

// 0 'a'
// 1 'b'
// 2 'c'

for...of ループの使用

js
const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']

疎配列を反復処理

entries() は空のスロットを undefined であるかのように処理します。

js
for (const element of [, "a"].entries()) {
  console.log(element);
}
// [0, undefined]
// [1, 'a']

配列でないオブジェクトに対する entries() の呼び出し

entries() メソッドは thislength プロパティを読み込み、そのキーが length よりも小さい非負の整数である各プロパティにアクセスします。

js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: "d", // length が 3 なので entries() からは無視される
};
for (const entry of Array.prototype.entries.call(arrayLike)) {
  console.log(entry);
}
// [ 0, 'a' ]
// [ 1, 'b' ]
// [ 2, 'c' ]

仕様書

Specification
ECMAScript Language Specification
# sec-array.prototype.entries

ブラウザーの互換性

BCD tables only load in the browser

関連情報