如何设置转换成数组? [英] How to convert Set to Array?

查看:112
本文介绍了如何设置转换成数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置似乎是一个很好的方式来创建有保证的独特元素数组,但它不公开任何好的办法来获得性能,除了发电机[设置] .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

 让阵列= Array.from(MYSET);

简单<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/S$p$pad_operator\"><$c$c>s$p$pading在数组中设置了

 让阵列= [... 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循环(这似乎并没有在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 array

let 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆