手写JS数组中的map方法,前端笔试

  • Post author:
  • Post category:其他


手写map,实现this指向的改变



1.源码

Array.prototype.jlMap= function(fn,thisArg){
     //先判断参数类型
    if(typeof fn !== 'function'){
        throw new TypeError('type is error');
    }
    //获取调用时的数组
    let array =this;
    const resArr=[];  //存放结果
    if(thisArg){      //当传入相应的this指向时
        array.forEach((currentValue,index)=>{      //遍历原数组
           const resault= fn.call(thisArg,currentValue,index,array);   //回调 并获取结果
            if(!resault){                      //回调结果
                throw new Error(' it is should behave  a returned value ');
            }
            resArr.push(resault);
        })
    }
    if(!thisArg){
        array.forEach((currentValue,index)=>{
           const resault= fn(currentValue,index,array);       //直接执行
            if(!resault){
                throw new Error(' it is should behave  a returned value ');
            }
            resArr.push(resault);
        })
    }
    return resArr;
}
//测试代码---------------------------------
let test = [1,12,2,34,4,5,5,66,7];

try{
    let q = test.jlMap( function(item){        //若需要改变this指向 ,不要用箭头函数 
        console.log(item*2);
        console.log(this)
        return item*2;
    },{arg:'456'}
    );
    console.log(q)
}
catch(err){
    console.log(err)
}

如果对你有帮助,请点个赞吧



版权声明:本文为F_fengzilin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。