此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in English Always switch to English

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 ⁨2015年7月⁩.

keys() 方法會回傳一個包含陣列中的每一個索引之鍵(keys)的新 Array Iterator 物件。

嘗試一下

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

語法

arr.keys()

回傳值

一個新的 Array 迭代器(iterator)物件。

範例

鍵迭代器不會乎略陣列中的空元素

js
var arr = ["a", , "c"];
var sparseKeys = Object.keys(arr);
var denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys); // [0, 1, 2]

規範

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.keys

瀏覽器相容性

參見