简体   繁体   中英

In JavaScript array reduce, what does the accumulator and value actually mean?

I dont understand how this code returns 10 and how its even called as a function because it does not display anything in my browser. What is the first accumulator when this code runs, if its 1, why not 0 because the first value of the array is 0.

[0, 1, 2, 3, 4].reduce(
  function (
    accumulator
    currentValue
) {
 return accumulator + currentValue;
});

The accumulator is the net result of the function. It contains either the initial value or the return value of the last call.

The current value is just the element being worked against.

In your current example, the accumulator is 0 since you have not provided an initial value and .reduce will use the first item.

 let run = 1; let result = [0, 1, 2, 3, 4, 5].reduce(function(acc, val) { console.log('run', run++, 'acc', acc, 'val', val); return acc + val; }); console.log('result', result);

However, notice in this example, providing an initial value, the callback gets hit an initial time for 0 .

 let run = 1; let result = [0, 1, 2, 3, 4, 5].reduce(function(acc, val) { console.log('run', run++, 'acc', acc, 'val', val); return acc + val; }, 0 /* initial value */); console.log('result', result);

reduce does "fold" the array by repeatedly applying the function:

[0, 1, 2, 3, 4].reduce(f, start)
// is
f(f(f(f(f(start, 0), 1), 2), 3), 4)

The first parameter is called "accumulator" because you can accumulate a value that will eventually be returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM