JavaScript之高阶函数

高阶函数(Higher-order function),满足下两个任意一个条件即为高阶函数:

  • 接受一个或多个函数作为参数输入
  • 输出一个函数

一、函数作为参数

JavaScript语言中内置了一些高阶函数,比如:Array.prototype.mapArray.prototype.filterArray.prototype.reduce,它们接收一个函数作为参数,并应用这个函数到列表的每一个元素。

Array.prototype.map


有一个数组[1,2,3,4],想要生成一个新的数组,其每个元素是之前数组的两倍:
不使用高阶函数:

const arr1 = [1,2,3,4,5];
const arr2 = [];
for(let i =0;i <arr1.length;i++){
    arr2.push(arr1[i] * 2)
}

console.log(arr1)   //[ 1, 2, 3, 4, 5 ]
console.log(arr2)   //[ 2, 4, 6, 8, 10 ]

使用高阶函数:

const arr1 = [1,2,3,4,5];
const arr2 = arr1.map(item=>item*2)

console.log(arr1)   //[ 1, 2, 3, 4, 5 ]
console.log(arr2)   //[ 2, 4, 6, 8, 10 ]

Array.prototype.filter


对于一个数组[1,2,2,3,4,5,6,6]去重:
不使用高阶函数:

const arr1 = [1,2,2,3,4,5,6,6];
const arr2 = [];
for(let i =0;i<arr1.length;i++){
    if( arr1.indexOf(arr1[i]) === i){
        arr2.push(arr1[i])
    }
}

console.log(arr1);  //[ 1, 2, 2, 3, 4, 5, 6, 6 ]
console.log(arr2);  //[ 1, 2, 3, 4, 5, 6 ]

使用高阶函数:

const arr2 = arr1.filter((item,index)=>{
    return arr1.indexOf(item)===index
})

console.log(arr1);  //[ 1, 2, 2, 3, 4, 5, 6, 6 ]
console.log(arr2);  //[ 1, 2, 3, 4, 5, 6 ]

Array.prototye.reduce


计算一个数组[0,1,2,3,4]各个元素的和。
不使用高阶函数:

const arr1 = [0,1,2,3,4];
let sum = 0;
for(let i=0;i<arr1.length;i++){
    sum += arr1[i]
}

console.log(sum);   //10
console.log(arr1)   //[ 0, 1, 2, 3, 4 ]

使用高阶函数:

const arr1 = [0,1,2,3,4];
const sum = arr1.reduce((accumulator, currentValue)=>{
    return accumulator+currentValue
})

console.log(arr1);  //[ 0, 1, 2, 3, 4 ]
console.log(sum);  //10

上面的是不使用initialValue,还可以使用initialValue

const arr1 = [0,1,2,3,4];
const sum = arr1.reduce((accumulator, currentValue)=>{
    return accumulator+currentValue
},10)

console.log(arr1);  //[ 0, 1, 2, 3, 4 ]
console.log(sum);  //20

二、函数作为返回值输出

isType函数


可以通过Object.prototype.toString.call来获取对应对象返回的字符串来准确判断数据类型。
封装一个高阶函数,能方便地使用:

const isType = type => obj => {
    return Object.prototype.toString.call(obj) === `[object ${type}]`
}

console.log(isType('Array')([1,2,3]))   //true
console.log(isType('Object')({a:'a'}))  //true

add函数

常见面试题,用JS实现一个无限累加的函数add, 实例如下:

add(1); // 1
add(1)(2);  // 3
add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10 

// 以此类推

实现代码:

function add(a){
    function sum(b){    //使用一个闭包
        a = a + b;
        return sum;
    }
    sum.toString = function(){
        return a;
    }
    return sum;
}

console.log(add(1))         //1
console.log(add(1)(2))      //3
console.log(add(1)(2)(3))   //6

console.log一个函数,实际上会调用***toString()**方法,只需要重写sum.toString()方法返回变量a就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值