JS用Array.reduce 实现 Array.map 和 Array.filter

一、实现Array.map

1、先用for 循环来实现下Array.prototype.map:

    Array.prototype.selfMap = function(){
        const ary = this
        const result = []
        const [fn,thisArg] = [].slice.call(arguments)
        if(typeof fn !== 'function'){
            throw new TypeError(fn + 'is not a function')
        }
        for(let i=0;i
JS用Array.reduce 实现 Array.map 和 Array.filter_第1张图片

2、用Array.reduce实现

    Array.prototype.reduceMap = function(){
        const ary = this
        const result = []
        const [fn, thisArg] = [].slice.call(arguments)

        if(typeof fn !=='function' ){
            throw new TypeError(fn + 'is not a function')
        }

        return ary.reduce(function(total,val,index){
            return total.concat(fn.call(thisArg,val,index,ary))
        },[])
    };

    //验证
    console.log([1,2,3,4].reduceMap(function(item){
        console.log(this)
        return item + 2
    },{msg:'aaa'}))
JS用Array.reduce 实现 Array.map 和 Array.filter_第2张图片

二、实现Array.filter

1、for循环实现:

    Array.prototype.selfFilter = function(){
        const ary = this
        const result = []
        const [fn , thisArg] = [].slice.call(arguments)
        let temp;
        for(let i=0;i3
    },{msg:'bbb'}))
JS用Array.reduce 实现 Array.map 和 Array.filter_第3张图片

2、用Array.reduce实现

    Array.prototype.reduceFilter = function(){
        const ary = this;
        const result = []
        const [fn,thisArg] = [].slice.call(arguments)

        return ary.reduce(function(total,val,index){
            return fn.call(thisArg,val,index,ary)? total.concat(val) : total
        },[])
    }

    //验证
    console.log([1,2,3,4,5,6,7].reduceFilter(function(item,index,arr){
        return item >3
    },{msg:'bbb'}))

你可能感兴趣的:(JS用Array.reduce 实现 Array.map 和 Array.filter)