我想要每个单独的返回值从reduce()函数,而不是总数

I want each individual return value from the reduce() function rather than the total

本文关键字:函数 单独 返回值 reduce 我想要      更新时间:2023-09-26
      previousValue currentValue    index         array      return value
first call       0        1               1          [0, 1, 2, 3, 4]    1
second call      1        2               2          [0, 1, 2, 3, 4]    3
third call       3        3               3          [0, 1, 2, 3, 4]    6
fourth call      6        4               4          [0, 1, 2, 3, 4]    10

我想要数组中的1,3,6,10而不是返回的总10。返回每个调用

可以将返回值压入数组,如下所示。它违背了函数式编程,因为它会使results产生副作用。但它确实符合你的需要。

var array = [0, 1, 2, 3, 4];
var results = [];
array.reduce(function(previousValue, currentValue) {
    var newValue = previousValue + currentValue;
    results.push(newValue);
    return newValue;
});
// result is 1,3,6,10
alert(results);

不要使用reduce。对数组切片,移动一个值以开始一个小计,然后使用map.

var arr = [0, 1, 2, 3, 4], output = arr.slice(), subtotal = output.shift()
output = output.map(function(elem) { return subtotal += elem })
// output is [1, 3, 6, 10]

Edit -实际上,这可以很好地与reduce一起工作,甚至比上面更简洁:

var arr = [0, 1, 2, 3, 4]
arr.reduce(function(a, b, ndx) { return a.length ? a.concat(a[ndx - 2] + b) : [a + b]})
// returns [1, 3, 6, 10]