The keys method generates and returns a fresh iterator object that contains the key for each index within the array. This method leaves the original array unchanged.
Syntax
array.keys();
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
Below is a straightforward implementation of the keys method within an array.
<httml>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
let arr=['Mon','Tue','Wed','Thu','Sat'];
let itr=arr.keys();
document.write(itr+"<br>");
//Looping through each key.
for (let key of itr) {
document.write(key+"<br>");
}
</script>
</body>
</html>
Output:
Thus, each element in the array is assigned a key based on the total count of elements it contains.
Example2
Implementing the keys function while accounting for gaps within the array.
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var arr = ['Mon','Tue','Wed',,'Fri']; //A hole is present in-between the elements.
var itr=arr.keys()
document.write(itr+"<br>");
for(let key of itr)
document.write(key+"<br>");
</script>
</body>
</html>
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
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
const arr=['a','b','c','d'];
const itr=arr.keys();
for(const key of itr)
document.write(key+"<br>");
</script>
</body>
</html>
Output:
Example4
Below is an illustration of how to create keys for a user-defined array.
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var arr=[]; //Creating a user-define array.
for(i=0;i<5;i++)
arr[i]=prompt("Enter any five elements"+(i+1));
document.write("The elements entered by the user are: <br>");
for(i=0;i<5;i++){
document.write(arr[i]);
document.write("<br>");
}
function create(){
var itr=arr.keys();
document.write("Keys generated are: <br>");
for(key of itr)
document.write(key+"</br>");
} //This function will generate keys for the array elements.
</script>
<input type="button" onClick="create()" value="Get Keys"/>
</body>
</html>
Output:
At the outset, the user will enter the elements via a prompt dialog box, which will be shown as:
Upon selecting the Get Keys button, the keys will be produced in the following format:
Consequently, the keys method serves as a straightforward means of producing keys for the values within an array.