js01之高阶函数与部分数组方法的实现

什么是高阶函数?

一个函数中有参数是函数,或者返回值是函数,这样的函数就是高阶函数。

下面这个例子中的fn就是高阶函数

const callback = ()=>{
    console.log('我是fn的参数');
}
const fn = (callback)=>{
    callback();
}

fn(callback);

我们平常使用的高阶函数有哪些呢?

其实有很多高阶函数,比如数组中的方法forEach,map,every,some等等都是高阶函数,还有react-redux中的connect函数也是高阶函数,其使用形式:connect()(Component)。

我们自己来写一下这几个数组方法的实现。

因为每一个数组都可以调用这些方法,所以这些方法写在原型上是最好的。

forEach的实现

Array.prototype.myForEach = function (callback) {
    if (!Array.isArray(this)) {
        throw new Error(`${array} is not a Array`);
    }
    if (typeof callback!== 'function') {
        throw new Error(`${callback} is not a Function`);
    }

    let that = this;
    for (let i = 0; i < that.length; i++) {
        callback(that[i]);//return 或者 break或者continue 没有用是应为每次的循环都是在一个函数内部进行的
    }
}

const arr = [1, 2];
arr.myForEach((item)=>{
    console.log(item);
});

 map的实现

Array.prototype.myMap = function(fn){
    if(!Array.isArray(this)){
        throw new Error(`${this} is not a Array`);
    }
    if(typeof fn !== 'function'){
        throw new Error(`${fn} is not a Function`);
    }

    let newArr = [];
    for(const value of this){
        newArr.push(fn(value));
    }
    return newArr;
}

const result = [1,2,3];
console.log(result.myMap(item=>item*item));

every的实现

Array.prototype.myEvery = function(callback){
    if(!Array.isArray(this)){
        throw new Error(`${this} is not a Array`);
    }
    if(typeof callback!== 'function'){
        throw new Error(`${callback} is not a Function`);
    }

    let flag = true;
    for(const value of this){
        flag = callback(value);
        if(!flag){
            break;
        }
    }
    return flag;
}

const arr = [1,2,3];
const result1 = arr.myEvery((item)=>item>0);
const result2 = arr.myEvery((item)=>item>1);
console.log(result1);
console.log(result2);

some的实现 

Array.prototype.some = function(fn){
    if(!Array.isArray(this)){
        throw new Error(`${this} is not a Array`);
    }
    if(typeof fn !== 'function'){
        throw new Error(`${fn} is not a Function`);
    }

    let flag = false;
    for(const value of this){
        flag = fn(value);
        if(flag){
            break;
        }
    }
    return flag;
}
const arr = [1,2,3];
console.log(arr.some((item)=>item>-1));
console.log(arr.some((item)=>item>4));

 

 数组中有很多方法的原理都是如此,把每一个元素通过用传入的回调函数进行处理,这样可以让函数变得更加灵活。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值