Sak*_*ham 2 javascript ecmascript-6
我想知道为什么下例中的索引array.reduce()从1开始而不是0
([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11Run Code Online (Sandbox Code Playgroud)
如果不将值作为第二个参数传递,则累加器将采用第一个值:
// add a vlaue to start
([11,22,33,44]).reduce((acc, val, index) => console.log(val), 0);
// now all values are iteratedRun Code Online (Sandbox Code Playgroud)
如果您记录累加器,则可以看到如何在没有第二个arg的情况下使用所有值:
// 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)Run Code Online (Sandbox Code Playgroud)
Cause.reduce被设计为无需初始累加器即可工作:
[1, 2, 3].reduce((a, b) => a + b)
Run Code Online (Sandbox Code Playgroud)
为此,第一次迭代a将是第一个元素和第二个元素,下一个元素将采用前一个结果和第三个值。b
如果传递初始累加器作为第二个参数,它将从索引 0 开始。