Created
December 24, 2020 20:45
-
-
Save oliverjumpertz/2227e79d5b3c1eb6d8e5bd12be5e10a9 to your computer and use it in GitHub Desktop.
Iterating over values and indices with a for..of-loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Iterating over the array with each individual element at hand while separately | |
// keeping track of the index. | |
let i = 0; | |
for (const element of array) { | |
console.log(i++, element); | |
} | |
// Array.prototype.entries() returns an iterator that returns an array instead | |
// of each individual element each time next() is called. | |
// By using array destructuring, we take the tuple (array) the iterator returns on | |
// each iteration step and destructure it into individual variables. | |
// We can now iterate over the array while having the index and the element at hand on | |
// each iteration. | |
for (const [index, element] of array.entries()) { | |
console.log(index, element); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment