使用 reduce 实现数组 map 方法

  //使用 reduce 实现数组 map 方法
    const selfMap2 = function (fn, context){
        let arr = Array.prototype.slice.call(this)
        // 这种实现方法和循环的实现方法有异曲同工之妙,利用reduce contact起数组中每一项
        // 不过这种有个弊端,会跳过稀疏数组中为空的项
        return arr.reduce((pre, cur, index) => {
            return [...pre, fn.call(context, cur, index, this)]
        }, [])
    }

    Array.prototype.selfMap = selfMap2
    var arr1 = [1, 2, 3]
    arr1.length = 5

    let arrMap = arr1.selfMap(function (x) {
        return x * 2
    })
    // [2, 4, 6]

 

posted @ 2019-06-24 23:03  来亦何哀  阅读(1973)  评论(0编辑  收藏  举报