The keys() method in JavaScript is used to create a new array iterator object that contains the keys for each index in the array. This iterator can then be used to iterate over the keys of the array.
Syntax
array.keys();
Parameters
This method does not accept any parameters.
Return Value
Return Type | Description |
---|---|
Array Iterator | An array iterator object containing the keys of the array. |
Example 1: Using keys() to Get Array Keys
This code demonstrates how to use the keys() method to get an iterator for the keys of an array.
let fruits = ['Apple', 'Banana', 'Orange']; let keys = fruits.keys(); for (let key of keys) { console.log(key); } // Output: // 0 // 1 // 2
Example 2: Using keys() with Array.from() Method
You can convert the array iterator into an array using Array.from() to get an array of keys.
let fruits = ['Apple', 'Banana', 'Orange']; let keysArray = Array.from(fruits.keys()); console.log(keysArray); // Output: [0, 1, 2]
Example 3: Using keys() with for…of Loop
You can also directly use the keys() iterator with a for…of loop to iterate over the keys of the array.
let fruits = ['Apple', 'Banana', 'Orange']; for (let key of fruits.keys()) { console.log(key); } // Output: // 0 // 1 // 2
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
38 | 12 | 28 | 25 | 8 |