sevenLee
11/17/2015 - 9:17 AM

(1)_.reduce (2)Array.Prototype.reduce() From https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

var sum = [1, 2, 3].reduce(
  function(total, num){ return total + num }
  , 0);
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
    return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]

I just started exploring the JavaScript Underscore library more in-depth and just want to clarify what I think _.reduce() (also known as inject and foldl) does is right. My question is: is the below right?

When _.reduce([1, 2, 3, 4, 5], function(memo, num) { return memo + num; }, 5);is called, the following happens:

memo starts at 5

memo + list[0] = memo = 6
memo + list[1] = memo = 8
memo + list[2] = memo = 11
memo + list[3] = memo = 15
memo + list[4] = memo = 20

And that is why the ran function returns 20. Is that right? And therefore _.reduceRight() is the opposite and starts from memo + list[ /* last element in array */ ]?

Thanks.