将 Javascript 可迭代转换为数组 [英] Transforming a Javascript iterable into an array

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

问题描述

我正在尝试使用新的 Map 对象来自Javascript EC6,因为它已在最新的 Firefox 和 Chrome 版本中得到支持.

I'm trying to use the new Map object from Javascript EC6, since it's already supported in the latest Firefox and Chrome versions.

但我发现它在函数式"编程中非常有限,因为它缺少经典的映射、过滤器等方法,这些方法可以很好地与 [key, value] 对配合使用.它有一个 forEach 但不返回回调结果.

But I'm finding it very limited in "functional" programming, because it lacks classic map, filter etc. methods that would work nicely with a [key, value] pair. It has a forEach but that does NOT returns the callback result.

如果我可以将它的 map.entries() 从 MapIterator 转换成一个简单的数组,我就可以使用标准的 .map, .filter 没有额外的黑客.

If I could transform its map.entries() from a MapIterator into a simple Array I could then use the standard .map, .filter with no additional hacks.

是否有一种好"的方法可以将 Javascript 迭代器转换为数组?在 python 中,它就像做 list(iterator) 一样简单...但是 Array(m.entries()) 返回一个数组,其中 Iterator 作为它的第一个元素!!!

Is there a "good" way to transform a Javascript Iterator into an Array? In python it's as easy as doing list(iterator)... but Array(m.entries()) return an array with the Iterator as its first element!!!

编辑

我忘了说明我正在寻找一个适用于 Map 的任何地方的答案,这意味着至少是 Chrome 和 Firefox(Array.from 在 Chrome 中不起作用).

I forgot to specify I'm looking for an answer which works wherever Map works, which means at least Chrome and Firefox (Array.from does not work in Chrome).

附注.

我知道有很棒的 wu.js 但它对 traceur 的依赖让我失望...

I know there's the fantastic wu.js but its dependency on traceur puts me off...

推荐答案

您正在寻找新的 Array.from 函数 将任意可迭代对象转换为数组实例:

You are looking for the new Array.from function which converts arbitrary iterables to array instances:

var arr = Array.from(map.entries());

现在 支持 Edge、FF、Chrome 和 Node 4+.

当然,在迭代器接口上直接定义mapfilter和类似的方法可能是值得的,这样你就可以避免分配数组.您可能还想使用生成器函数而不是高阶函数:

Of course, it might be worth to define map, filter and similar methods directly on the iterator interface, so that you can avoid allocating the array. You also might want to use a generator function instead of higher-order functions:

function* map(iterable) {
    var i = 0;
    for (var item of iterable)
        yield yourTransformation(item, i++);
}
function* filter(iterable) {
    var i = 0;
    for (var item of iterable)
        if (yourPredicate(item, i++))
             yield item;
}

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

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