JavaScript Array keys() method
The keys()
method in JavaScript is used to create a new array iterator object that contains the keys (or indices) of each element in an array. This method is particularly useful when you need to access the indices of the elements without needing their corresponding values.
Syntax:
Return Value:
- A new
Array Iterator
object that contains the keys (indices) of the array.
Key Points:
- The
keys()
method does not modify the original array. - The resulting iterator can be traversed using methods like
next()
, or it can be used in a loop (such as afor...of
loop) to iterate over the keys.
Example 1: Basic usage
Example 2: Using a for...of loop
You can easily iterate over the keys using a for...of
loop:
Example 3: Converting to an Array
If you want to convert the iterator into an array of keys, you can use Array.from()
:
Example 4: Nested Arrays
The keys()
method can be used with nested arrays as well:
Summary:
- The
keys()
method provides a straightforward way to access the indices of elements in an array without needing their values. - It returns an iterator, allowing for flexible iteration over the indices in various contexts, such as loops and transformations.
- This method can simplify code that requires knowledge of the element positions within an array, making it useful for a variety of programming scenarios.