Iterator.prototype.reduce()
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
Iterator 实例的 reduce() 方法与 Array.prototype.reduce 类似:它对迭代器生成的每个元素执行用户提供的 "reducer" 回调函数,并传入前一个元素计算的返回值。在所有元素上运行减速器的最终结果是一个值。
¥The reduce() method of Iterator instances is similar to Array.prototype.reduce: it executes a user-supplied "reducer" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.
语法
参数
¥Parameters
callbackFn-
对迭代器生成的每个元素执行的函数。其返回值在下次调用
callbackFn时成为accumulator参数的值。对于最后一次调用,返回值变为reduce()的返回值。使用以下参数调用该函数:accumulator-
上次调用
callbackFn所产生的值。第一次调用时,如果指定了后者,则其值为initialValue;否则它的值是迭代器的第一个元素。 currentValue-
当前元素的值。在第一次调用时,如果指定了
initialValue,则其值为迭代器的第一个元素;否则其值为第二个元素。 currentIndex-
currentValue的索引位置。第一次调用时,如果指定了initialValue,则其值为0,否则为1。
initialValueOptional-
第一次调用回调时
accumulator被初始化的值。如果指定了initialValue,则callbackFn将从第一个元素作为currentValue开始执行。如果未指定initialValue,则accumulator被初始化为第一个元素,callbackFn以第二个元素作为currentValue开始执行。在这种情况下,如果迭代器为空(因此没有第一个值作为accumulator返回),则会引发错误。
返回值
例外情况
描述
¥Description
有关 reduce() 如何工作的详细信息,请参阅 Array.prototype.reduce()。与大多数其他迭代器辅助方法不同,它不能很好地处理无限迭代器,因为它不是惰性的。
¥See Array.prototype.reduce() for details about how reduce() works. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy.
示例
使用 reduce()
¥Using reduce()
以下示例创建一个迭代器,该迭代器生成斐波那契数列中的项,然后对前十项求和:
¥The following example creates an iterator that yields terms in the Fibonacci sequence, and then sums the first ten terms:
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
console.log(
fibonacci()
.take(10)
.reduce((a, b) => a + b),
); // 143
规范
| Specification |
|---|
| Iterator Helpers # sec-iteratorprototype.reduce |
浏览器兼容性
BCD tables only load in the browser