假设您有一个类似数组的 Javascript ES6 Iterable,您事先知道它的长度是有限的,将其转换为 Javascript 数组的最佳方法是什么?
这样做的原因是很多js库如underscore和lodash只支持数组,所以如果你想在Iterable上使用它们的任何函数,必须先将它转换为数组。
在 python 中,您可以只使用 list() 函数。 ES6 中是否有等效项?
最佳答案
您可以使用 Array.from或 spread syntax (...) .
例子:
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 ]
关于javascript - 将 ES6 可迭代对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27612713/