Array.prototype.keys
Returns the indexes of an array.
Available since: ES2015
Syntax
array.keys()Return value
IteratorAn iterator of the array indexes.
Examples
The indexes as an array:
console.log([...['a', 'b', 'c'].keys()]);Output:
[
0,
1,
2
]A quick way to get a range 0..n-1:
console.log([...Array(5).keys()].join(' '));Output:
0 1 2 3 4Notes
Do not confuse it with Object.keys(): that one returns an array of strings, this one an iterator of numbers.
See also
- Array.prototype.entries — Returns index–element pairs for a for...of loop.
- Array.from — Creates an array from a string, Set, Map or another iterable.
- Object.keys — Returns an array of an object's property names.
Related recipes
In the tutorial
- Iterating over arrays — How to go through every element of an array in JavaScript: the for loop, for...of, forEach and entries.