Created
November 2, 2020 23:22
-
-
Save DoctorDerek/9b2c7821ec42d7945b3536d769783e3e to your computer and use it in GitHub Desktop.
Three methods to iterate through a JavaScript ES6 Set object
This file contains 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
const emojiSet = new Set(["🙋🏼", "🦾", "🦿", "🙋🏼"]) | |
// Use Set.prototype.keys() or Set.prototype.values() | |
const emojiIterator = emojiSet.values() | |
// You can use a for...of loop with an Iterator object | |
for (const emoji of emojiIterator) { | |
console.log(emoji) | |
} | |
// emojiSet.keys() is equivalent to: emojiSet.values() | |
for (const emoji of emojiSet.keys()) { | |
console.log(emoji) | |
} | |
// Output: "🙋🏼", "🦾", "🦿" | |
// Use Set.prototype.forEach() with a Callback Function | |
emojiSet.forEach((emoji) => { | |
console.log(emoji) | |
}) | |
// Output: "🙋🏼", "🦾", "🦿" | |
// Use a for...of Loop Directly With the New Set | |
for (const emoji of emojiSet) { | |
console.log(emoji) | |
} | |
// Output: "🙋🏼", "🦾", "🦿" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment