如何设置转换成数组? [英] How to convert Set to Array?
问题描述
设置似乎是一个很好的方式来创建有保证的独特元素数组,但它不公开任何好的办法来获得性能,除了发电机[设置] .values,这就是所谓的中 mySet.values.next的尴尬方式()
。
本就OK了,如果你能叫地图
和设置类似的功能。但你不能做到这一点,也是如此。
我试过 Array.from
,但似乎只转换阵列状(节点列表和TypedArrays?)对象数组。另一个尝试: Object.keys
不为集工作,Set.prototype没有类似的静态方法
因此,问题:是否有与值创建一个数组任何方便的内置方法一组给定(元素的顺序并不重要)
?。如果没有这样的选择存在,那么也许有一个很好的习惯单行这样做呢?像,使用为...的
,或类似的?
如果没有这样的选择存在,那么也许有一个很好的习惯
单行这样做呢?像,使用...或类似的?
块引用>事实上,有几种方法来转换一个集来一个<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\">Array:
的使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\"><$c$c>Array.from$c$c>
让阵列= Array.from(MYSET);
的简单<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/S$p$pad_operator\"><$c$c>s$p$pading$c$c>在数组中设置了的
让阵列= [... MYSET]
的旧的方式方法,迭代和推到一个新的数组(套确实有
的forEach
)的让阵列= [];
mySet.forEach(V =&GT;的Array.push(ⅴ));的使用票友<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\"><$c$c>for...of$c$c>循环(这似乎并没有在Chrome中工作了)的
让阵列= [V为(MYSET的V)];
Set seems like a nice way to create Arrays with guaranteed unique elements, but it does not expose any good way to get properties, except for generator [Set].values, which is called in an awkward way of
mySet.values.next()
.This would have been ok, if you could call
map
and similar functions on Sets. But you cannot do that, as well.I've tried
Array.from
, but seems to be converting only array-like (NodeList and TypedArrays ?) objects to Array. Another try:Object.keys
does not work for Sets, and Set.prototype does not have similar static method.So, the question: Is there any convenient inbuilt method for creating an Array with values of a given Set ? (Order of element does not really matter).
if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using
for...of
, or similar ?解决方案if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?
Indeed, there are several ways to convert a Set to an Array:
using
Array.from
let array = Array.from(mySet);
Simply
spreading
the Set out in an arraylet array = [...mySet];
The old fashion way, iterating and pushing to a new array (Sets do have
forEach
)let array = []; mySet.forEach(v => array.push(v));
Using a fancier
for...of
loop (this doesn't seem to work in Chrome anymore)let array = [v for (v of mySet)];
这篇关于如何设置转换成数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!