关于reduce()
reduce()语法:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
arr.reduce((accumulator,curValue,curIndex,arr)=>{
return accumulator+curValue
},initialValue)
- accumulator 累计器
- currentValue 当前值
- currentIndex 当前索引
- array 数组
如果提供了initialValue,accumulator取值为initialValue,currentValue取值数组中第一个值
如果没有提供initialValue,accumulator取值数组中第一个值,currentValue取值数组中第二个值
- 求数组累计值
let arr = [1,2,3,4,5]
let newArr = []
let one = arr.reduce((accumulator,currentValue,currentIndex,array)=>{
newArr.push(accumulator+currentValue)
return accumulator+currentValue
})
console.log(newArr,one) //[3, 6, 10, 15] 15
- 求对象累计值
let arr = [{x:1}, {x: 2}, {x: 3},{x:4},{x:5}]
let newArr = []
let one = arr.reduce((accumulator,currentValue,currentIndex,array)=>{
console.log(accumulator,currentValue.x,accumulator+currentValue.x)
if(accumulator !== 0){
newArr.push(accumulator+currentValue.x)
}
return accumulator+currentValue.x
},0)
console.log(newArr,one) //[3, 6, 10, 15] 15
- 去重
let arr = [2,3,1,3,3,2];
let newArr = arr.reduce((accumulator,currentValue)=>{
console.log(accumulator,currentValue,'11111111')
if(!accumulator.includes(currentValue)){ // 累计值查找不到当前值的话,当前值拼接到累计值中
return accumulator.concat(currentValue)
}else{
return accumulator
}
},[])
console.log('newArr',newArr) //[2, 3, 1]
newArr = newArr.sort((first,second)=>{ return first - second}) // 升序
console.log('newArr',newArr) //[1,2,3]
- 求元素的次数
const arr = ['A', 'B', 'T', 'B', 'A'];
let one = arr.reduce( (accumulator, currentValue) => {
if (currentValue in accumulator) {
console.log(accumulator,'currentValue')
accumulator[currentValue]++;
} else {
accumulator[currentValue] = 1;
}
return accumulator;
}, {});
console.log(one) // {A: 2, B: 2, T: 1}
待续。。。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)