问题描述
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。所以要返回每个调用
1楼
Ed Ballot
1
已采纳
2015-07-25 18:13:44
您可以像这样将返回值推入数组。
它与功能编程相反,因为它会将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);
2楼
Curtis Autery
0
2015-07-25 20:36:23
不要为此使用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]