在可迭代对象上使用数组方法

问题描述 投票:0回答:1

[我想知道是否存在一种/简单的方法来使用全局JavaScript Array对象的方法,例如Array.prototype.map对象上的Array.prototype.reduceArray.prototype.filter甚至是Iterables。或至少不需要创建临时数组。

我已经在Mozilla网站,StackOverflow,Google,GitHub等上进行了搜索,但是没有找到任何答案。


实际示例:

假设我要计算从sum到某个数字“ 1”(例如num)的所有数字的10

我在想

  1. 使用Iterator / Generator function来获得所需的数字,一一(在下面的示例中为Generator
  2. 然后使用Array.prototype.reduce()之类的方法对其进行总结。

这对我来说是可行的,因为这类方法(reduce)一次使用一个值,然后在操作完成时要求下一个值,这与Streams中的Java非常相似。这正是Iterable的功能。

mySum(10); // returns 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

/**
 * Sums all the number from 1 to the provided number
 * @param num {number} the maximum number to include in the sum
 * @returns the sum of all numbers from 1 to the provided number
 */
function mySum(num) {

    function* myGenerator() {
        for(let i = 1; i <= num; ++i) {
            yield i;
        }
    }

    return myGenerator().reduce((previous, current) => previous + current, 0);

}

上面的这段代码显然不起作用,因为Iterable没有reduce方法。但是为什么迭代器没有一个?

是否有避免像下面这样创建临时数组的方法?

mySum(10); // returns 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

/**
 * Sums all the number from 1 to the provided number
 * @param num {number} the maximum number to include in the sum
 * @returns the sum of all numbers from 1 to the provided number
 */
function mySum(num) {

    function* myGenerator() {
        for(let i = 1; i <= num; ++i) {
            yield i;
        }
    }

    return Array.from(myGenerator()).reduce((previous, current) => previous + current, 0); // notice here the change

}
javascript arrays stream iterable
1个回答
0
投票

不确定这是best的方式(我的生成器经验有限)-但是这种方式没有临时数组

function mySum(num) {

    function* myGenerator() {
        for(let i = 1; i <= num; ++i) {
            yield i;
        }
    }
    let sum = 0;
    const gen = myGenerator();
    let value, done;
    while(({value, done} = gen.next()) && !done) {
      sum += value;
    }
    return sum;
}
console.log(mySum(10));
© www.soinside.com 2019 - 2024. All rights reserved.