// 根本用法
let arr = [1, 2, 3, 4]
let sum = arr.reduce((init, item, i, k) => {console.log(init, "inits")
//init 默认为数组第一项,一次累加数组项,最初返回一项。// console.log(item) // 数组中的每一项
// console.log(i,"here") // 下标
// console.log(k,"k") // 原数组
return init + item
})
console.log(sum)
// 数组去重
let arrs = [11, 11, 2, 3, 3]
let newArr = arrs.reduce((prev, cur, index, arr) => {prev.indexOf(cur) === -1 && prev.push(cur);
return prev;
}, []);
// 扁平一个二维数组
let arrs1 = [[1, 2, 8],
[3, 4, 9],
[5, 6, 10]
];
let res = arrs1.reduce((x, y) => x.concat(y), []);
// 多维数组扁平
function steamroller3(arr) {return arr.reduce((prev, next) => {return prev.concat(Array.isArray(next) ? steamroller3(next) : next)
}, [])
}
// compose 函数实现简洁版本
function func1(a) {console.log(a, "hewew")
return a * 10;
}
function func2(b) {console.log(b, "bbbbb")
return b * 2
}
function func3(c) {return c / 2;}
const compose = (...func) => (...init) =>
func.reduce((prev, curr, index) => curr(prev),
...init
);
const a1 = compose(func1, func2)(2);
console.log(a1) //40
const a2 = compose(func1, func2, func3)(2);
console.log(a2) //20
*** 该办法用于拆分简单业务逻辑比方购物车的各种梯队流动计算。应用组合函数拆分逻辑单元不便每一个 task 单元测试及缩小代码耦合 ***
// 数组最大值
let max = arr.reduce((prev, cur) =>Math.max(prev,cur))