Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 911
Randomblue Avatar asked May 06 '13 14:05

Randomblue


People also ask

How do you iterate over a set?

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.

Can we iterate over sets?

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...

Can you iterate over a set in Python?

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.

Can you iterate over a set C++?

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.


2 Answers

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.

like image 190
andyrandy Avatar answered Oct 22 '22 06:10

andyrandy


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); } 
like image 23
bizi Avatar answered Oct 22 '22 08:10

bizi