javascript-手写Array.prototype.filter()和Array.prototype.map()

loading 2023年03月01日 126次浏览

比较简单,filter接受两个参数,一个fn回调函数,一个this值指定执行fn时this对象(可选)。fn接收item,index,arr等参数。

        Array.prototype.myFilter = function(fn , thisArg = window){
            if(!Array.isArray(this)) throw new TypeError('...');
            let arr = this , res = [];
            // 逐个判断原数组 如果符合条件则加入res中
            for(let i = 0 ; i < arr.length ; i++){
                if(fn.call(thisArg , arr[i] , i , arr)){
                    res.push(arr[i]);
                }
            }
            return res;
        }

        let arr = [1,2,3,4,5];
        console.log(arr.filter((item) => item > 2));

把map和filter放在一起是因为两个基本一样,只不过一个是过滤出符合条件的元素,一个是对所有元素进行处理而已:

        Array.prototype.myMap = function(fn , thisArg = window){
            if(!Array.isArray(this)) throw new TypeError('...');
            let arr = this , res = [];
            for(let i = 0 ; i < arr.length ; i++){
                res[i] = fn.call(thisArg , arr[i] , i , arr);
            }
        }

        let arr = [1,2,3,4,5];
        console.log(arr.map((item) => item * 2));