简体   繁体   English

如何使用数组构造Set

[英]How do I construct a Set with an Array

I am playing with Set in Node.JS v0.11.3 and the --harmony flag. 我摆弄Set在node.js中v0.11.3和--harmony标志。 The API works fine, I can add , remove , clear , etc. I have however not been able to initialise a set with an array. API工作正常,我可以addremoveclear等。但是我无法初始化带有数组的集合。 I have tried (as prompted by the MDN page ) 我试过(根据MDN页面的提示)

var mySet = new Set([1, 1, 2]);

How can I convert an array to a set? 如何将数组转换为集合? Is MDN outdated? MDN过时了吗? Has Node.JS simply not implemented the feature? Node.JS有没有实现这个功能?

The v8 implementation of the Set constructor does not yet support the iterator and comparator arguments mentioned in §15.16.1.1 of the current draft of the Harmony specification , and node uses v8 as its JavaScript interpreter. Set构造函数的v8实现还不支持当前Harmony规范草案的 §15.16.1.1中提到的iteratorcomparator参数,并且节点使用v8作为其JavaScript解释器。

As a band-aid, you can use the simplesets package . 作为创可贴,您可以使用simplesets包

Works fine in v8 now using an array supplied to a constructor. 现在使用提供给构造函数的数组在v8中正常工作。 I'm using node v6.2.0 (v8 version 5.0.71.47). 我正在使用node v6.2.0(v8版本5.0.71.47)。

> let mySet = new Set([1,2,3]);
undefined
> mySet;
Set { 1, 2, 3 }

> for ( let key of mySet ) { console.log(key) }
1
2
3
undefined

> mySet.size
3

From what I have read it is my understanding that the implementation of this is new and experimental. 根据我的阅读,我的理解是,这项实施是新的和实验性的。 Some things might not work properly. 有些事情可能无法正常运作。 Also I have noted many instances where new features did not behave as expected until after a period of maturing. 此外,我已经注意到许多实例,其中新功能在经过一段时间的成熟后才表现出预期的效果。 It would be best to avoid this and simply add them manually if functionally is your goal. 如果功能上是您的目标,最好避免这种情况并简单地手动添加它们。

You can try this one: 你可以尝试这个:

Sample session: 示例会话:

> var sets = require('simplesets')
undefined
> var mySet = new sets.Set([1, 1, 2]);
undefined
> mySet
{ _items: [ 1, 2 ] }
> mySet.size()
2

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

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