admin管理员组

文章数量:1207738

I was wondering why the index in array.reduce() starts from 1 rather than 0 in the below example

([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11

I was wondering why the index in array.reduce() starts from 1 rather than 0 in the below example

([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11

Share Improve this question edited Sep 4, 2019 at 18:21 Saksham asked May 2, 2019 at 18:13 SakshamSaksham 9,3809 gold badges46 silver badges75 bronze badges 1
  • 6 If you don't pass a second argument, it starts at element 1 and passes element 0 as the accumulator value. – Pointy Commented May 2, 2019 at 18:14
Add a comment  | 

2 Answers 2

Reset to default 19

The accumulator takes the first value if you don't pass a value as the second argument:

// add a vlaue to start
([11,22,33,44]).reduce((acc, val, index) => console.log(val), 0);
// now all values are iterated

If you log the accumulator you can see how all the values are used without the second 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)

Cause .reduce is designed to work without an initial accumulator:

    [1, 2, 3].reduce((a, b) => a + b)

For this to work, a will be the first element and b the second one at the first iteration, the next one will take the previous result and the third value.

If you pass an initial accumulator as the second argument, it will start at index 0.

本文标签: javascriptWhy arrayreduce() starts from index 1Stack Overflow