将ES6 Iterable转换为Array

编程入门 行业动态 更新时间:2024-10-27 08:39:00
本文介绍了将ES6 Iterable转换为Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 假设你有一个类似数组的Javascript ES6 Iterable,你提前知道的长度是有限的,把它转换成Javascript数组的最好方法是什么?

这样做的原因是许多js库,如下划线和lodash只支持数组,所以如果你想在Iterable上使用任何他们的功能,它必须首先被转换成一个数组。

在python中,您只需使用list()函数即可。在ES6中有一个等价物吗?

解决方案

您可以使用 Array.from 或 spread operator 。

示例:

let s = new Set(); s.add(1); s.add(2); s.add(3); s.add(4); let a = Array.from(s); // = [1,2,3,4] let b = [... s]; // = [1,2,3,4]

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?

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.

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

解决方案

You can use Array.from or the spread operator.

Example:

let s = new Set(); s.add(1); s.add(2); s.add(3); s.add(4); let a = Array.from(s); // = [ 1, 2, 3, 4 ] let b = [...s]; // = [ 1, 2, 3, 4 ]

更多推荐

将ES6 Iterable转换为Array

本文发布于:2023-07-24 13:26:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1203710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   Iterable   Array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!