Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Array
  6. keys()

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

Thekeys() method ofArray instances returns a newarray iterator object that contains the keys for each index in the array.

Try it

const array = ["a", "b", "c"];const iterator = array.keys();for (const key of iterator) {  console.log(key);}// Expected output: 0// Expected output: 1// Expected output: 2

Syntax

js
keys()

Parameters

None.

Return value

A newiterable iterator object.

Description

When used onsparse arrays, thekeys() method iterates empty slots as if they have the valueundefined.

Thekeys() method isgeneric. It only expects thethis value to have alength property and integer-keyed properties.

Examples

Using keys() on sparse arrays

UnlikeObject.keys(), which only includes keys that actually exist in the array, thekeys() iterator doesn't ignore holes representing missing properties.

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]

Calling keys() on non-array objects

Thekeys() method reads thelength property ofthis and then yields all integer indices between 0 andlength - 1. No index access actually happens.

js
const arrayLike = {  length: 3,};for (const entry of Array.prototype.keys.call(arrayLike)) {  console.log(entry);}// 0// 1// 2

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp