将 ES6 可迭代转换为数组 [英] Convert ES6 Iterable to Array

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

问题描述

假设您有一个类似数组的 Javascript ES6 Iterable,您事先知道它的长度是有限的,那么将其转换为 Javascript 数组的最佳方法是什么?

Say you have an array-like Javascript ES6 Iterable that you know in advance will be finite in length, what's the best way to convert that to a Javascript Array?

这样做的原因是很多js库比如underscore和lodash都只支持Arrays,所以如果你想在Iterable上使用它们的任何一个函数,必须先把它转换成一个Array.

The reason for doing so is that many js libraries such as underscore and lodash only support Arrays, so if you wish to use any of their functions on an Iterable, it must first be converted to an Array.

在 python 中,你可以只使用 list() 函数.ES6 中是否有等价物?

In python you can just use the list() function. Is there an equivalent in ES6?

推荐答案

您可以使用 Array.from传播语法 (...).

示例:

const x = new Set([ 1, 2, 3, 4 ]);

const y = Array.from(x);
console.log(y); // = [ 1, 2, 3, 4 ]

const z = [ ...x ];
console.log(z); // = [ 1, 2, 3, 4 ]

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

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