zoukankan      html  css  js  c++  java
  • 使用 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]
    好记性不如烂笔头,看到自己觉得应该记录的知识点,结合自己的理解进行记录,用于以后回顾。
  • 相关阅读:
    asp.net读取/导入project(mpp)文件
    hdu2103
    hdu2100(大数加)
    hdu1406
    hdu1249
    hdu1038
    hdu2565
    hdu1203
    zoj3501
    hdu2102
  • 原文地址:https://www.cnblogs.com/wangxi01/p/11080110.html
Copyright © 2011-2022 走看看