假设我有一系列项目,我想通过 myReducer
函数(无论它是什么)执行归约操作。如果我的项目在一个数组中(比如 myArray
),这很容易:
myArray.reduce(myReducer);
但是,如果我的序列非常大并且我不想分配一个包含所有序列的数组,只是立即逐项减少怎么办?我可以为我的序列创建一个生成器函数,这部分很清楚。是否有一种直接的方法来执行减少操作?我的意思是除了自己为生成器编写 reduce 功能之外。
最佳答案
目前,ECMA-Script 标准为数组提供了类似 reduce
的函数,所以你运气不好:你需要为 实现你自己的 reduce
迭代:
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)
关于javascript - 减少 JavaScript 中生成器提供的一系列项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53450002/