Question

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?

Was it helpful?

Solution 7

The of operator doesn't appear to be currently supported in Chrome. It seems that only FireFox versions 13 through 18 support it. It also appears that none of the browsers actually support Set although the page does say that some of the tests represent existence and not full functionality or coherence. So it might be that Set is partially implemented in Chrome.

OTHER TIPS

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.

You can also use the spread operator to convert a Set into an array (an alternative to Array.from(yourSet)).

const mySet = new Set();

mySet.add('a');
mySet.add('b')

const iterableSet = [...mySet];
// end up with: ['a', 'b']

// use any Array method on `iterableSet`
const lettersPlusSomething = iterableSet.map(letter => letter + ' something');

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);
}

A simple functional approach is to just use forEach

const mySet = new Set([1, 2, 3])
mySet.forEach(a => { console.log(a) })
// 1 2 3

I use the forEach(..); function. (documentation)

Even if the syntactic sugar for iteration hasn't been implemented yet, you can probably still use iterators.

http://www.2ality.com/2012/06/for-of-ff13.html explains

The special method __iterator__ returns an iterator object. Such an object has a method next() that either returns the next element in the current iteration sequence or throws StopIteration if there are no more elements.

So you should be able to iterate over the set using

for (var it = mySet.__iterator__();;) {
  var element;
  try {
    element = it.next();
  } catch (ex) {
    if (ex instanceof StopIteration) {
      break;
    } else {
      throw ex;
    }
  }
  // Do something with element
}

You can also define a functional version of for…of like

function forOf(collection, f) {
  // jQuery.each calling convention for f.
  var applyToElement = f.bind(/* this */ collection, /* index */ void 0);
  for (var it = collection.__iterator__();;) {
    var element;
    try {
      element = it.next();
    } catch (ex) {
      if (ex instanceof StopIteration) {
        break;
      } else {
        throw ex;
      }
    }

    // jQuery.each return convention.
    if (applyToElement(element) === false) { break; }
  }
}

this worked for me

mySet.forEach(async(item) =>{
   await doSomething(item)
 })

@bizi's answer is close but it did not work for me. This worked on Firefox:

var s= new Set([1,2]),
     it = s.values();
 for (var val= it.next().value; val=it.next().value;) {
     console.log("set: "+val);
 }
let set = new Set();
set.add(1);
set.add(2);

// This will be an array now, now you can loop normally.
console.log([...set]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top