# 数组reduce方法的高级技巧

``````var  arr = [1, 2, 3, 4, 5];
sum = arr.reduce(function(prev, cur, index, arr) {
console.log(prevres, cur, index);
return prevres + cur;
})
console.log(arr, sum);``````

``````1 2 1
3 3 2
6 4 3
10 5 4
[1, 2, 3, 4, 5] 15``````

1. prev: 第一项的值或上一次叠加的结果值
2. cur: 当前会参与叠加的项
3. index： 当前值的索引
4. arr: 数组本身

``````var result = [
{
subject: 'math',
score: 88
},
{
subject: 'chinese',
score: 95
},
{
subject: 'english',
score: 80
}
];``````

``````var sum = 0;
for(var i=0; i<result.length; i++) {
sum += result[i].score;
}``````

``````var sum = result.reduce(function(prev, cur) {
return cur.score + prev;
}, 0);``````

``````var sum = result.reduce(function(prev, cur) {
return cur.score + prev;
}, -10);``````

``````var dis = {
math: 0.5,
chinese: 0.3,
english: 0.2
}

var sum = result.reduce(function(prev, cur) {
return cur.score + prev;
}, -10);

var qsum = result.reduce(function(prev, cur) {
return prev + cur.score * dis[cur.subject]
}, 0)

console.log(sum, qsum);``````

``````
var arrString = 'abcdaabc';

arrString.split('').reduce(function(res, cur) {
res[cur] ? res[cur] ++ : res[cur] = 1
return res;
}, {})
``````

``````[1, 2].reduce(function(res, cur) {
res.push(cur + 1);
return res;
}, [])``````

12.6k 声望
2.7k 粉丝
0 条评论