【问题标题】:Use Array methods on Iterables在 Iterables 上使用数组方法
【发布时间】:2020-08-29 01:28:20
【问题描述】:

我想知道是否有一种方法/一种简单的方法可以使用全局 JavaScript Array 对象的方法,例如 Array.prototype.mapArray.prototype.reduce 甚至 Array.prototype.filter 上的 Iterables 对象。或者至少,不需要创建临时数组。

我在 Mozilla 网站、StackOverflow、Google、GitHub 等上进行了全面搜索……但没有找到任何答案。


实际例子:

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

我在想

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

这对我来说是可行的,因为这类方法 (reduce) 一次使用一个值,然后在操作完成时请求下一个值,很像 Java 中的 Streams。这正是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

}

【问题讨论】:

  • 不用reduce 也可以求和,但您似乎想要一个同时使用生成器和reduce 的解决方案。那正确吗?你能写你自己的reduce方法吗?
  • @ggorlen > 你想要一个同时使用生成器和减少的解决方案。那正确吗?对,就是这样。在迭代器上使用我们在数组上使用的一些方法不是很好吗?我知道我可以在没有reduce 的情况下对数字求和,但reduce 似乎也足够通用,可以应用于迭代器。我会尝试为迭代器编写一个自定义 reduce 函数。

标签: javascript arrays stream iterable


【解决方案1】:

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

function mySum(num) {

    function* myGenerator() {
        for(let i = 1; i <= num; ++i) {
            yield i;
        }
    }
    let sum = 0;
    for(let value of myGenerator()) {
      sum += value;
    }
    return sum;
}
console.log(mySum(10));

【讨论】:

    猜你喜欢
    • 2014-06-09
    • 2015-12-05
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2021-03-04
    • 2019-10-02
    • 2017-10-02
    相关资源
    最近更新 更多