Array.prototype.map重现

let arr=[1,2,3,4,5];
    //在数组显示原型上定义自定义方法
    Array.prototype.newMap=function(func){
        //定义新数组用来接收回调函数返回值
        let arr=[];
        //for循环遍历数组
        for(let i=0;i<this.length;i++){
            //新数组接收返回值
            arr[arr.length]=func(this[i],i,this);
        }
        //返回新数组
        return arr;
    }
    //定义新变量接收NewMap方法的返回值,同时调用NewMap方法并给其传值
    let result=arr.newMap(function(item,idx,curArr){
        //这里的返回值会被新数组接收
        return item*2;
    })
    console.log(result);

有问题欢迎大家指出!

posted @ 2022-03-24 14:48  听风小弟  阅读(32)  评论(0)    收藏  举报