How to Iterate over the Elements of a Set in JavaScript ?
In JavaScript, you can iterate over the elements of a Set using various methods, such as the forEach()
method, the for...of
loop, or by converting the Set to an array and using array iteration methods.
- Using
forEach()
method:let mySet = new Set([1, 2, 3, 4, 5]);
mySet.forEach(function(value) {
console.log(value);
}); - Using
for...of
loop:let mySet = new Set([1, 2, 3, 4, 5]);
for (let value of mySet) {
console.log(value);
} - Converting Set to Array and using array iteration methods:
let mySet = new Set([1, 2, 3, 4, 5]);
// Convert Set to an array using the spread operator
let myArray = [...mySet];
// Use array iteration methods on the array
myArray.forEach(function(value) {
console.log(value);
});
Contact Us