var arr = [1,2,3,4,5]
有什么方法可以让其中,后向前求和
就是最后得到的数组其中每项之前的综合
[1,3,6,10,15]
reduce有四个参数,index代表当前处理值的下标:
var arr = [1,2,3,4];
var newArr = arr.reduce(function(prevValue,currentValue,index,array){
prevValue.push( currentValue + ( index > 0 ? prevValue[index - 1]: 0 ) );
return prevValue;
},[])
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
function(total,currentValue, index,arr) 必需。用于执行每个数组元素的函数。
函数参数:
let iArr=[1,2,3,4,5];
iArr.reduce(function(total, currentValue, currentIndex, arr){
let temp = total.length?total[total.length-1]:0;
total.push(currentValue+temp);
return total;
},[]);
ECMAScript 5 以上
[1, 2, 3, 4, 5].reduce(function(a, b) {
a.push(b + (a[a.length - 1] || 0));
return a;
}, []);
10 回答11.2k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.3k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决