array.reduce(function(pre, currentValue, currentIndex, arr), initialValue)
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;
});
console.log(arr, sum);
打印结果
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10
上面的例子index是从1开始的,第一次的prev的值是数组的第一个值。数组长度是4,reduce函数循环3次。
接下来给initvalue赋予初始值0
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;
}, 0);
console.log(arr, sum);
打印结果
0 1 0
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10
这个例子index是从0开始的,第一次的prev的值是我们设置的初始值0,数组长度是4,reduce函数循环4次。
总结:如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
return prev * cur;
}, 1);
console.log(arr, sum);
打印结果
[ 1, 2, 3, 4 ] 24
var arr = ["one", "two", "three", "six", "four", "five", "six"];
var newArr = arr.reduce((pre, cur) => {
console.log(cur, pre);
if (cur in pre) {
pre[cur]++;
} else {
pre[cur] = 1;
}
return pre;
}, {});//这里注意初始值要默认赋予空对象,不然会报错
console.log(newArr);
打印结果
one {}
two { one: 1 }
three { one: 1, two: 1 }
six { one: 1, two: 1, three: 1 }
four { one: 1, two: 1, three: 1, six: 1 }
five { one: 1, two: 1, three: 1, six: 1, four: 1 }
six { one: 1, two: 1, three: 1, six: 1, four: 1, five: 1 }
{ one: 1, two: 1, three: 1, six: 2, four: 1, five: 1 }
let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
if(!pre.includes(cur)){
return pre.concat(cur)
}else{
return pre
}
},[])
console.log(newArr);
打印结果
[1, 2, 3, 4]
let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
return pre.concat(cur)
},[])
console.log(newArr);
打印结果
[0, 1, 2, 3, 4, 5]
let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr = function(arr){
return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr(cur):cur),[])
}
console.log(newArr(arr));
打印结果
[0, 1, 2, 3, 4, 5, 6, 7]
var result = [
{
subject: 'math',
score: 10
},
{
subject: 'chinese',
score: 20
},
{
subject: 'english',
score: 30
}
];
var sum = result.reduce(function(prev, cur) {
return cur.score + prev;
}, 0);
console.log(sum)
打印结果
60