JavaScript Array keys() Method
The keys() method creates and returns a new iterator object which holds the key for every index in the array. This method does not affect the original array.
Syntax
Parameter
It does not hold any parameter.
Return
It returns a new array iterator object.
JavaScript Array keys() Example
Let’s see some examples to understand better.
Example1
Here’s the simple implementation of keys() method in array.
Output:
So, according to the number of elements present in the array, a key is assigned to each one.
Example2
Implementing keys() method with holes in between the array.
Output:
Note: It is clear from the above example that Array keys() method does not ignore the holes present as an array element in the given array. It assigns a key value to that empty hole too. Also, the keys are assigned in an increasing order sequence to each element.
Example3
Output:
Example4
Here’s an example to generate keys for a user-define array.
Output:
Initially, the user will input the elements through prompt box which will be displayed as:
After clicking on Get Keys button, the keys will be generated as:
Thus, keys() method is a direct approach forgenerating keys for the array values.