arr.reduce(function(prev, cur, index, arr) {
})
prev: 第一项的值或者上一次叠加的结果值
cur: 当前会参与叠加的项
index: 当前值的索引
arr: 数组本身
1.用于数组中每个数相加求和
var arr = [1,2,3,4,5,6,7]
function total(arr){
return arr.reduce((preValue,currentValue)=>{
console.log(preValue,currentValue)
return preValue+currentValue
})
}
console.log(total(arr))//28
function total(...arr){//...arr是将数组展开
return arr.reduce((preValue,currentValue)=>{
console.log(preValue,currentValue)
return preValue+currentValue
})
}
console.log(total(1,2,3,4,5)) //15
2.将数组中的项的值加倍,然后只选择那些大于50的项
const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {
num = num * 2; //(map)
//filter number > 50
if (num > 50) {
finalList.push(num);
}
return finalList;
}, []);
doubledOver50; // [60, 80]
注意:reduce参数添加了第二个参数
这第二个参数就是设置prev的初始类型和初始值,比如为0,就表示prev的初始值为number类型,值为0,因此,reduce的最终结果也会是number类型
3.求一个字符串中每个字符出现的次数
var arrString = 'abcdaabc';
console.log(arrString.split(''))
arrString.split('').reduce(function (res, cur) {
console.log(res, cur)
res[cur] ? res[cur]++ : res[cur] = 1
return res;
}, {})
4.数组去重
let log = console.log.bind(console);
let person = [
{id: 0, name: "小明"},
{id: 1, name: "小张"},
{id: 2, name: "小李"},
{id: 3, name: "小孙"},
{id: 1, name: "小周"},
{id: 2, name: "小陈"},
];
let obj = {};
person = person.reduce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
log(person);