使用ES5阵列方法与ES6发生器 [英] Using ES5 array methods with ES6 generators

查看:92
本文介绍了使用ES5阵列方法与ES6发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ES6发生器的新ES5阵列功能的正确方法是什么?我必须首先将iterable显式转换为数组,还是有更好的方法?例如:

  function * range(low,high){
var i = low;
while(i< high)
yield i ++;
}

//范围内数字的总和,不起作用
console.log(range(0,10).reduce((x,y)=> x + y));


解决方案

生成器函数返回 Iterator 对象。 Iterator API不包括更高阶的Array方法,例如 map reduce 等,所以你需要构建一个中间阵列(或使用像 wu.js 的图书馆)。



您可以使用扩展操作符从(有限)迭代器简洁地构建一个数组:

  var sum = [... range(0 ,10)]。reduce((e,i)=> e + i)


What's the correct way of using the new ES5 array functions with ES6 generators? Do I have to explicitly convert the iterable into an array first, or is there a better way? For example:

function* range(low, high) {
    var i = low;
    while(i < high)
        yield i++;
}

// Sum of numbers in range, doesn't work
console.log(range(0, 10).reduce((x,y) => x + y));

解决方案

Generator functions return Iterator objects. The Iterator API does not include higher order Array methods such as map, reduce etc, so you need to build an intermediate Array (or use a library like wu.js).

You can use the spread operator to concisely build an Array from a (finite) iterator:

var sum = [...range(0, 10)].reduce((e, i) => e + i)

这篇关于使用ES5阵列方法与ES6发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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