The keys() method of Array instances returns a new array iterator object that contains the keys for each index in the array.
The keys() method of Array instances returns a new array iterator object that contains the keys for each index in the array.
keys()
None.
A new iterable iterator object.
When used on sparse arrays, the keys() method iterates empty slots as if they have the value undefined.
The keys() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Unlike Object.keys(), which only includes keys that actually exist in the array, the keys() iterator doesn't ignore holes representing missing properties.
const arr = ["a", , "c"]; const sparseKeys = Object.keys(arr); const denseKeys = [...arr.keys()]; console.log(sparseKeys); // ['0', '2'] console.log(denseKeys); // [0, 1, 2]
The keys() method reads the length property of this and then yields all integer indices between 0 and length - 1. No index access actually happens.
const arrayLike = { length: 3, }; for (const entry of Array.prototype.keys.call(arrayLike)) { console.log(entry); } // 0 // 1 // 2
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
keys |
38 | 12 | 28 | 25 | 8 | 38 | 28 | 25 | 8 | 3.0 | 38 | 1.0 | 0.12.0 | |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys