Using ES5 array methods with ES6 generators

前端 未结 3 1558
刺人心
刺人心 2020-12-20 16:28

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?

3条回答
  •  一生所求
    2020-12-20 17:23

    Build the array using Array.from:

    console.log(Array.from(range(0, 10)).reduce((x,y) => x + y));
    

    Array.from creates an array from an iterable. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from.

    If you want to do the reduce without creating the array, then you'll end up needing to do something like:

    var sum = 0;
    for (e of range(0, 10)) sum += e;
    

提交回复
热议问题