为什么我的javascript减少函数返回太多的数字,当它涉及到0



使用reduce函数,这应该返回9000,但它如何返回256000?我之前测试过类似的代码,它工作得很好

function combined(...s) {
return s.flat().reduce(x => x + x)
}
console.log(combined([1000, 1000, 1000], [1000, 1000, 1000], [1000, 1000, 1000]))

reduce通常有2个参数,在您的示例中,x保存累积值,而我添加的第二个参数y将是迭代中的当前值。你必须这样使用它:

function combined(...s){
return s.flat().reduce((x, y) => x + y)
}
console.log(combined([1000,1000,1000],[1000,1000,1000],[1000,1000,1000]))

Array.reduce()回调函数至少需要2个参数:accumulatorcurrentValue

还可以将初始值传递给accumulator,在本例中应该是0

function combined(...s){
return s.flat().reduce((result, x) => result + x, 0)
}
console.log(combined([1000,1000,1000],[1000,1000,1000],[1000,1000,1000]))

在您的示例中,x代表用数组的第一个元素初始化的accumulator:1000,您基本上返回accumulator + accumulator,结果如下:

- 2000 (1000 + 1000)
- 4000 (2000 + 2000)
- 8000 (4000 + 4000)
...
- 256000 (128000 + 128000)

最新更新