使用 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]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM