Iterate over set elements
I have turned on the Chrome flag for experimental ECMAscript 6 features, one of which is Set
. As I understand, the details of Set
are broadly agreed upon by the spec writers.
I create a set a
and add the string 'Hello'
a = Set();
a.add('Hello');
but how do I iterate over the elements of a
?
for(let i of a) { console.log(i); }
gives "SyntaxError: Illegal let
declaration outside extended mode"
for(var i of a) { console.log(i); }
gives "SyntaxError: Unexpected identifier"
for(var i in a) { console.log(i); }
gives Undefined
Is it possible to iterate over of a set in Chrome 26?
Solution 1:
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.
Solution 2:
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);
}
Solution 3:
I use the forEach(..);
function. (documentation)
Solution 4:
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))