函数式编程 -- 高阶函数

高阶函数

  • 高阶函数(Hiner-order function),可以把函数作为参数传递给另一个函数,也可以把函数作为另一个函数的返回结果
// 函数作为参数
function forEach(array,fn){
    for(let i = 0; i < array.length; i++){
      fn(array[i])
    }
}
// 测试
let arr=[1, 3, 4, 5, 7]
forEach(arr, function(item){
  console.log(item)
})
// 函数作为返回值,这里once使fn只执行一次
function once(fn){
    let done = false
    return function(){
      if(!done){
          done = true
          return fn.apply(this, arguments)
      }
    }
}
// 测试
let pay=once(function(money){
    console.log("支付:" + money + "RMB"
})

pay(5)
pay(5)

// 输出
// 支付:5RMB

常用高阶函数

  • forEach

  • map

  • filter

  • every

  • some

  • find/findIndex

  • reduce

  • sort
    ...

  • 都些函数都有一个共同点 -- 需要接收一个函数作用参数

  • 下面模拟一下map方法

// map
const map = (array,fn)=>{
    let results = []
    for(let value of array){
        results.push(fn(value))
    }
    return results
}

// 测试
let arr = [1, 3, 4 ,6]
arr = map(arr,v => v*v)
console.log(arr)

// 输出
// [1, 9, 16, 36]
原文地址:https://www.cnblogs.com/MissSage/p/14875332.html