对数组进行遍历,然后组成合适的参数传递给回调函数,过程就是一个函数pipeline
1.Reduce
JavaScript 函数式编程实践指南 - 修言 - 掘金小册
const arr = [1, 2, 3]
const initialValue = 0
const add = (previousValue, currentValue) =>previousValue+currentValue;
//执行顺序 0 + 1 + 2 + 3
const sumArr = arr.reduce(add,0);
console.log(sumArr) //expected output: 6
执行过程:
2.map
function add1AndPush(previousValue, currentValue) {
// previousValue 是一个数组
previousValue.push(currentValue + 1)
return previousValue
}
const arr = [1,2,3]
const newArray = arr.map((num)=> num+1)
const newArray1 = arr.reduce(add1AndPush,[])
console.log(newArray);//[2, 3, 4]
console.log(newArray1);//[2, 3, 4]
3.compose
执行顺序是从右往左,也就是执行顺序是:func4 => func3 => func2 => func1
compose(
func1,
func2,
func3,
func4
)(value)
4.pipe
执行顺序是从左往右,也就是执行顺序是:func1 => func2 => func3 => func4
const funcs = [func1, func2, func3, func4]; pipe(...funcs)(value);