如何将集合转换为数组? [英] How to convert Set to Array?

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

问题描述

Set 似乎是创建具有保证唯一元素的数组的好方法,但它没有公开任何获取属性的好方法,除了生成器 [Set].values,它在mySet.values.next() 的尴尬方式.

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().

如果你能在 Sets 上调用 map 和类似的函数,那就没问题了.但你也不能那样做.

This would have been ok, if you could call map and similar functions on Sets. But you cannot do that, as well.

我尝试过 Array.from,但似乎只将类数组(NodeList 和 TypedArrays ?)对象转换为数组.另一个尝试:Object.keys 不适用于 Sets,并且 Set.prototype 没有类似的静态方法.

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.

那么,问题是:是否有任何方便的内置方法来创建具有给定 Set 值的数组?(元素的顺序并不重要).

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).

如果不存在这样的选项,那么也许有一个很好的惯用单线来做到这一点?比如,使用 for...of 或类似的 ?

if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?

推荐答案

如果不存在这样的选项,那么也许有一个很好的惯用语单行这样做吗?像,使用 for...of 或类似的?

if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?

确实,有几种方法可以转换 SetArray:

Indeed, there are several ways to convert a Set to an Array:

使用 Array.from

let array = Array.from(mySet);

简单地传播 数组中的设置

let array = [...mySet];

老式的方式,迭代并推送到一个新数组(集合确实有 forEach)

let array = [];
mySet.forEach(v => array.push(v));

以前,使用非标准的、现在已弃用的数组理解语法:

let array = [v for (v of mySet)];

这篇关于如何将集合转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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