借鑒:http://www.reibang.com/p/e375ba1cfc47
2019-06-28 reduce學(xué)習(xí)
說明:reduce(callback,init)丧凤。
callback有四個(gè)參數(shù):prev(上次調(diào)用返回的值或者是init)溺欧,cur(當(dāng)前的值),index(當(dāng)前值的索引)柿隙,arry(調(diào)用reduce的數(shù)組)
init:第一次調(diào)用callback的第一個(gè)函數(shù)
用法:
1顶滩、初始值提供余掖?
arr = [1,2,3,4]; arr.reduce(callback,init)
不提供init值,reduce從索引1的地方執(zhí)行callback
提供init值0礁鲁,reduce從索引0的地方執(zhí)行callback
2盐欺、數(shù)組為空,初始值提供仅醇?
arr=[];arr.reduce(callback,init)
不提供init值冗美,直接報(bào)錯(cuò)"TypeError: Reduce of empty array with no initial value"
提供init值0,不報(bào)錯(cuò)
3析二、求和:
arr.reduce((x,y)=>x+y)
4粉洼、求乘積
arr.reduce((x,y)=>x*y)
5、求元素出現(xiàn)次數(shù)
let names = ['zhangsan','lisi','wangwu','lisi']
let nameNum = names.reduce((pre,cur)=>{
if(cur in pre){
pre[cur]++
} else {
pre[cur]=1
}
return pre
},{})
6叶摄、數(shù)組去重
let names = ['zhangsan','lisi','wangwu','lisi'];
let newArr = names.reduce((pre,cur)=>{
if(!pre.includes(cur)){
return pre.concat(cur)
} else {
return pre
}
},[])
7属韧、將二維數(shù)組轉(zhuǎn)換為一維數(shù)組
let arr = [[0,1],[2,3],[4,5]];
let newArr = arr.reduce((pre,cur)=>{
return pre.concat(cur)
},[])
8、將多維數(shù)組轉(zhuǎn)換為一維
let arr = [0,[1,2],[3,[4,5]]];
let newArr = (arr)=>{
arr.reduce((pre,cur)=>{
pre.concat(Array.isArray(cur)?newArr(cur):cur)
},[])
}
9蛤吓、對象里的屬性求和
let result = [{name:'zhangsan',age:12},{name:'lisi',age:14},{name:'wangwu',age:18}];
let ageSum = result.reduce((pre,cur)=>{
pre = cur.age+pre
},0)