Ond*_*dra 6 javascript reduce generator
假设我有一系列项目,我想通过myReducer函数(无论它是什么)执行归约操作。如果我的项目在一个数组中(比如myArray),这很容易:
myArray.reduce(myReducer);
Run Code Online (Sandbox Code Playgroud)
但是,如果我的序列非常大并且我不想分配所有它的数组,只是为了立即逐项减少它怎么办?我可以为我的序列创建一个生成器函数,这部分很清楚。有没有一种直接的方法来执行减少?我的意思是除了自己为生成器编写 reduce 功能之外。
目前,ECMA-Script 标准提供了类似于reduce数组的函数,所以你运气不好:你需要reduce为iterables实现你自己的函数:
const reduce = (f, i, it) => {
let o = i
for (let x of it)
o = f (o, x)
return o
}
const xs = [1, 2, 3]
const xs_ = {
[Symbol.iterator]: function* () {
yield 1
yield 2
yield 3
}
}
const output1 = reduce ((o, x) => o + x, 10, xs)
const output2 = reduce ((o, x) => o + x, 10, xs_)
console.log ('output1:', output1)
console.log ('output2:', output2)Run Code Online (Sandbox Code Playgroud)