是否有可能使用上ES6实例集数组迭代法? [英] Is it possible to use array iteration methods on ES6 Set instances?
问题描述
我使用ES6实例集,我需要应用在他们一些转换。这些是如果他们的阵列,这将是简单的那种变革。下面是一个例子:
I am using ES6 Set instances and I need to apply some transformations on them. These are transformations of the kind that would be simple if they were arrays. Here is an example:
let s = new Set;
s.add(1);
s.add(2);
s.add(3);
let n = s.filter(val => val > 1); // TypeError, filter not defined
let n = Array.prototype.filter.call(s, val => val > 1); // []
我希望结果会是个新设置或数组。我同样想使用其他阵列COM prehension方法,如过滤
,地图
,减少
等。而我也想对ES6地图实例类似的行为也是如此。
I was hoping that the result would either be a new Set or an array. I similarly want to use other array comprehension methods like filter
, map
, reduce
, etc. And I would also like to have similar behaviour on ES6 Map instances as well.
这是可能的,或者我需要使用香草JS数组?
Is this possible, or do I need to be using vanilla JS arrays?
推荐答案
您可以用得到的数组S的值
you can get the values of s in an array using
Array.from(s.values())
<一个href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from\">Array.from文档说,它从一个阵列状或迭代对象创建一个新的Array实例。
Array.from documentation states that it creates a new Array instance from an array-like or iterable object.
<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/values\">Set.values返回包含在插入顺序设置对象中的每个元素的值一个新的Iterator对象。
Set.values returns a new Iterator object that contains the values for each element in the Set object in insertion order.
所以你的code变为
let s = new Set;
s.add(1);
s.add(2);
s.add(3);
let n = Array.from(s.values()).filter(val => val > 1)
这篇关于是否有可能使用上ES6实例集数组迭代法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!