In this article, you will learn about the javascript Array built-in method Array.prototype.keys()
. How does this method work in javascript?
The Array.prototype.keys()
method returns a new array iterator that contains the keys for each index in the calling array.
array.keys();
This method takes no parameter. And This method does not change the original array.
If you used this method on sparse arrays, then this method iterates empty slots as if they have the value undefined
.
Here are some examples of Array.prototype.keys()
method:
//Here some examples of Array.keys() Method
const arr = ['Java', 'C#', 'Python', 'SQL Server'];
const arrIterator = arr.keys();
for (const key of arrIterator) {
console.log(key);
}
/*
--Expected Output--
0
1
2
3
*/
//Using keys() on sparse arrays
const arr1 = ['Java', , 'C#', 'Python', undefined, 'SQL Server', null];
const sparseKeys = Object.keys(arr1);
for (const key of sparseKeys) {
console.log(key);
}
/*
As you can see in the example, it skip the index of the empty slot,
but it returns the indexes for undefined or null.
--Expected Output--
"0"
"2"
"3"
"4"
"5"
"6"
*/
const denseKeys = [...arr1.keys()];
for (const key of denseKeys) {
console.log(key);
}
/*
As you can see in the example, if you use arr.keys() with the spread operator
then it will not skip the index of the empty slot,
as well as the indexes for undefined or null.
--Expected Output--
0
1
2
3
4
5
6
*/
I hope this article will help you to understand the javascript Array built-in method Array.prototype.keys().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments