JavaScript Array.keys() Method
-
Syntax of JavaScript
Array.keys()
: -
Example Code: Use the
Array.keys()
Method With the Array of Numbers -
Example Code: Compare the Output of the
Object.keys()
andarray.keys()
Methods
In JavaScript, the array.keys()
method is used to get the keys of every index of the reference array. The method creates the new iterable object and embeds all the keys of the current array.
Syntax of JavaScript Array.keys()
:
let arr = ["Hello", "Delft", 30];
let iterableObject = arr.keys();
Parameters
This method doesn’t take any parameter values.
Return
The Array.keys()
method returns the new iterable object of all keys of the arr
.
Example Code: Use the Array.keys()
Method With the Array of Numbers
In the example below, we created the array of numbers. We have used the array.keys()
method to get the iterable object of keys of all indexes of the array.
You can see in the output that iterable
is an object and array iterator. Also, we are iterating through the iterable
object using the for
loop and printing the iterable
object’s values.
let arr = [20,40,50];
let iterable = arr.keys();
console.log(iterable);
for(let x of iterable){
console.log(x);
}
Output:
Object [Array Iterator] {}
0
1
2
Example Code: Compare the Output of the Object.keys()
and array.keys()
Methods
We have created the array of strings in this example. The array also contains some empty elements.
When we find the keys of the array indexes using the Object.keys(arr)
method, it ignores the empty values, but the arr.keys()
method doesn’t.
The example below shows that the array contains the empty value at the third index. So, the returned object from the Object.keys(arr)
method doesn’t have the 2
key value as it ignores the empty value.
let refarr = ["Delft","stack", ,"Hello"];
let arrrayIterable = [...refarr.keys()];
console.log(arrrayIterable);
let Objectiterable = Object.keys(refarr);
console.log(Objectiterable);
Output:
[ 0, 1, 2, 3 ]
[ '0', '1', '3' ]