reduce()的一些实用方法

一、数组arr.reduce(function(prevValue,curValue,curIndex,array){
},initValue);
1.prevValue:上一次调用回调函数的返回值或者初始值initValue;
2.curValue:当前值;
3.curIndex:当前值的索引;
4.array:调用reduce的数组;
5.initValue:初始值。

二、经典用例:
let arr = [1,1,2,3,3,4];
1:数组去重
let arrRes = arr.reduce((p,c)=>{
  if(!p.includes(c)){
return p.concat(c);
}else{
return p;
}
},[])
console.log(arrRes)//[1,2,3,4];

2.统计数组元素出现次数
let arrNum = arr.reduce((p,c)=>{
if(!p[c]){
p[c] = 1;
}else{
p[c]++;
}
return p;
},{})
console.log(arrNum)//{ '1': 2, '2': 1, '3': 2, '4': 1 };

嘿嘿,其实会发现用其他循环方法也都能实现,只是一种多的思路。

 

posted @ 2021-02-25 13:45  你风致  阅读(158)  评论(0编辑  收藏  举报