Iterate over set elements
A very easy way is to turn the Set into an Array first:
let a = new Set();
a.add('Hello');
a = Array.from(a);
...and then just use a simple for loop.
Be aware that Array.from
is not supported in IE11.
I use the forEach(..);
function. (documentation)
There are two methods you can use. for...of and forEach
let a = new Set();
a.add('Hello');
for(let key of a) console.log(key)
a.forEach(key => console.log(key))
Upon the spec from MDN, Set
has a values method:
The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order.
So, for iterate through the values, I would do:
var s = new Set(['a1', 'a2'])
for (var it = s.values(), val= null; val=it.next().value; ) {
console.log(val);
}