JavaScript Array keys() method is used to return a new array iterator object that contains the keys(indices) for each index in the array.
Syntax
array.keys()
Parameters
None.
Return value
Returns new iterable iterator object.
Visual Representation
Example 1: How to Use Array keys() Method
let countries = ['IND', 'SA', 'US','UK','AUS'];
let iteratorObj = countries.keys();
console.log(iteratorObj);
So, it has given us iteratorObj. We can get the values by iterating for..of() loop.
let countries = ['IND', 'SA', 'US','UK','AUS'];
let iteratorObj = countries.keys();
console.log(iteratorObj);
// looping through the iterator object
for (let key of iteratorObj) {
console.log(key);
}
Output
Object [Array Iterator] {}
0
1
2
3
4
Example 2: Passing an array filled with holes
The iterator object includes keys for all positions in the array, even if they are empty.
let countries = ['IND', , 'US','UK', ,];
let iteratorObj = countries.keys();
// looping through the iterator object
for (let key of iteratorObj) {
console.log(key);
}
Output
0
1
2
3
4
Supported Browsers:
- Google Chrome 38.0
- Microsoft Edge 12.0
- Mozilla Firefox 28.0
- Safari 8.0
- Opera 25.0