简体   繁体   English

迭代集合元素

[英]Iterate over set elements

I have turned on the Chrome flag for experimental ECMAscript 6 features, one of which is Set .我为实验性 ECMAscript 6 功能打开了 Chrome 标志,其中之一是Set As I understand, the details of Set are broadly agreed upon by the spec writers.据我了解,规范编写者广泛同意Set的细节。

I create a set a and add the string 'Hello'我创建了一个集合a并添加了字符串'Hello'

a = Set();
a.add('Hello');

but how do I iterate over the elements of a ?但是我如何迭代a的元素?

for(let i of a) { console.log(i); }

gives "SyntaxError: Illegal let declaration outside extended mode"给出“语法错误:扩展模式外的非法let声明”

for(var i of a) { console.log(i); }

gives "SyntaxError: Unexpected identifier"给出“语法错误:意外的标识符”

for(var i in a) { console.log(i); }

gives Undefined给出Undefined

Is it possible to iterate over of a set in Chrome 26?是否可以在 Chrome 26 中迭代一组?

A very easy way is to turn the Set into an Array first:一个非常简单的方法是先将 Set 变成一个数组:

let a = new Set();
a.add('Hello');
a = Array.from(a);

...and then just use a simple for loop. ...然后只需使用一个简单的 for 循环。

Be aware that Array.from is not supported in IE11.请注意Array.from在 IE11 中不受支持。

Upon the spec from MDN, Set has a values method:根据 MDN 的规范, Set有一个values方法:

The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order. values() 方法返回一个新的 Iterator 对象,该对象包含 Set 对象中按插入顺序排列的每个元素的值。

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(..);我使用forEach(..); function.功能。 ( documentation ) ( 文档)

There are two methods you can use.您可以使用两种方法。 for...of and forEach for...offorEach

let a = new Set();
a.add('Hello');

for(let key of a) console.log(key)

a.forEach(key => console.log(key))

The of operator doesn't appear to be currently supported in Chrome . Chrome 目前似乎不支持of运算符。 It seems that only FireFox versions 13 through 18 support it.似乎只有 FireFox 版本 13 到 18 支持它。 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.似乎没有一个浏览器实际上支持Set尽管该页面确实说某些测试代表存在而不是完整的功能或一致性。 So it might be that Set is partially implemented in Chrome.所以可能是在 Chrome 中部分实现了Set

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 http://www.2ality.com/2012/06/for-of-ff13.html说明

The special method __iterator__ returns an iterator object.特殊方法__iterator__返回一个迭代器对象。 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.这样的对象有一个方法next() ,它要么返回当前迭代序列中的下一个元素,要么在没有更多元素时抛出StopIteration

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您还可以定义 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; }
  }
}

A simple functional approach is to just use forEach一个简单的函数式方法是只使用forEach

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

this worked for me这对我有用

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

You can also use the spread operator to convert a Set into an array (an alternative to Array.from(yourSet) ).您还可以使用展开运算符将Set转换为数组( 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');
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. @bazi 的答案很接近,但对我不起作用。 This worked on Firefox:这适用于 Firefox:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM