我想知道为什么 array.reduce()
中的索引在下面的示例中从 1 而不是 0 开始
([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11
最佳答案
如果您没有将值作为第二个参数传递,则累加器将采用第一个值:
// add a vlaue to start
([11,22,33,44]).reduce((acc, val, index) => console.log(val), 0);
// now all values are iterated
如果您记录累加器,您可以看到所有值在没有第二个参数的情况下是如何使用的:
// Show accumulator return value
let final = ([11,22,33,44]).reduce((acc, val, index) => (console.log("acc:", acc, "val:", val), val));
// final is the last object that would have been the accumulator
console.log("final:", final)
关于javascript - 为什么 `array.reduce()` 从索引 1 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958051/