admin管理员组

文章数量:1133890

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?

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?

Share Improve this question edited May 11, 2013 at 8:53 Randomblue asked May 6, 2013 at 14:44 RandomblueRandomblue 116k150 gold badges362 silver badges556 bronze badges 4
  • 2 Looks like for-of is only supported in Firefox currently... – Mark Rushakoff Commented May 6, 2013 at 14:49
  • How to implement a Set in JavaScript – NullPointerException Commented May 6, 2013 at 14:56
  • can you use this: jsclass.jcoglan.com/set.html – Bass Jobsen Commented May 6, 2013 at 15:14
  • See Browser compatibility for Set.prototype[@@iterator]() in the MDN docs. – Wyck Commented Oct 24, 2021 at 4:16
Add a comment  | 

11 Answers 11

Reset to default 85

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.

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

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

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.

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

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

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)
 })
let set = new Set();
set.add(1);
set.add(2);

// This will be an array now, now you can loop normally.
console.log([...set]);

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

本文标签: javascriptIterate over set elementsStack Overflow