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?
Example 2: Iterate through Set using iterator() We have used the iterator() method to iterate over the set. Here, hasNext() - returns true if there is next element in the set. next() - returns the next element of the set.
There is no way to iterate over a set without an iterator, apart from accessing the underlying structure that holds the data through reflection, and replicating the code provided by Set#iterator...
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. There are numerous ways that can be used to iterate over a Set.
Iterate over a set using range-based for loop In this method, a range-based for loop will be used to iterate over all the elements in a set in a forward direction.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With