• 高阶函数使用原生js实现--持续补充


    高阶函数:一个接收函数作为参数或者将函数作为返回输出的函数。

    1.reduce

    reduce接收两个参数(函数和可选初始值initValue),可选初始值在构造函数,不能仅仅通过是否存在来判断,因为空字符串‘’和数字0,undefined,NaN都可以作为初始值,所以要通过判断参数个数确定初始值,初始值存在直接影响函数的执行次数,函数执行次数= initValue?数组长度-1:数组长度

            Array.prototype.reduce=function(fn,initValue){
                let result;
                let initIndex=0;
                if(arguments.length == 2){
                    result = initValue;
                 
                }else{
                    result = this[0]
                    initIndex = 1;
                }
                for(let i = initIndex;i<this.length;i++){
                    result= fn(result,this[i],i,this)
                }
                return result;
            }

    2.map

            Array.prototype.map=function(fn){
                // console.log(this)
                let arr = []
                this.forEach((em,index)=>{
                    em = fn(em,index,this)
                    arr.push(em)
                })
                return arr;
            }

    3.filter(参数和map一样,filter函数返回执行结果为true的值,这里函数判断为弱等于==)、

            Array.prototype.filter = function(fn){
                let arr = []
                this.forEach((el,index)=>{
                    let result = fn(el,index,this)
                    if(result) arr.push(el)
                })
                return arr;
            }
  • 相关阅读:
    staticmethod & classmethod
    stanford Python
    LD_LIBRARY_PATH
    Centos7.2 errors
    theano profile
    电梯开关量GPIO配置记录
    定时器配置 中断配置 GPIO
    电梯开发进度贴
    Makefile编写学习摘要
    数据挖掘聚类算法--Kmeans
  • 原文地址:https://www.cnblogs.com/freefy/p/12172006.html
Copyright © 2020-2023  润新知