Array.prototype.keys()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since May 2018.
試してみましょう
const array1 = ["a", "b", "c"];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
// Expected output: 0
// Expected output: 1
// Expected output: 2
構文
js
keys()
引数
なし。
返値
新しい反復可能なイテレーターオブジェクトです。
解説
例
疎配列に対する keys() の呼び出し
配列に実際に存在するキーだけを処理する Object.keys()
とは異なり、 keys()
イテレーターは見つからないプロパティを表す穴を無視しません。
js
const arr = ["a", , "c"];
const sparseKeys = Object.keys(arr);
const denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys); // [0, 1, 2]
配列以外のオブジェクトに対する keys() の呼び出し
keys()
メソッドは this
の length
プロパティを読み込み、 0 から length - 1
までのすべての整数インデックスを返します。実際にはインデックスアクセスは行われません。
js
const arrayLike = {
length: 3,
};
for (const entry of Array.prototype.keys.call(arrayLike)) {
console.log(entry);
}
// 0
// 1
// 2
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-array.prototype.keys |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
keys |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.