当前位置: 代码迷 >> JavaScript >> 我想从reduce()函数获得每个单独的返回值,而不是总计
  详细解决方案

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

热度:88   发布时间:2023-06-05 09:24:42.0
      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]

编辑-实际上,使用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]
  相关解决方案