• Array.forEach原理,仿造一个类似功能


    Array.forEach原理,仿造一个类似功能

    array.forEach

     // 设一个arr数组
            let arr = [12,45,78,165,68,124];
            let sum = 0;
            // 遍历该数组求和
            arr.forEach(function(item,index){
                sum += item;
            })
            console.log(sum);
    

    如上

    我们使用forEach可遍历一个数组,并取出其index,item,还有 数组本身

    然后根据返回的值可以实现你想要的功能,比如求和

    原理

    该函数的原理是利用了Array的原型对象进行操作的,下面是依据此原理模仿forEach的例子,以此来说明一下该方法的原理

    Array.prototype.myForEach = function (fn) {
            for (let i = 0; i < this.length; i++) {
                fn(this[i], i, this);
            }
        };
    

    也就是当我们调用一次myForEach函数时,其中的fn将会被调用this.length-1次(其中的this指的自然是调用该方法的对象)

    执行如下代码,可以发现输出结果确实与forEach一致

    let arr = [12, 45, 78, 165, 68, 124]; 
    Array.prototype.myForEach = function (fn) {
            for (let i = 0; i < this.length; i++) {
                fn(this[i], i, this);
            }
        };
        arr.myForEach(function (item, index, arr) {
            console.log("item:" + item + ",index:" + index + ",this:" + arr);
        })
    

    当我们在调试台打断点在arr.muForEach(function(item,index,arr))..这一行时,再一步一步调试可以发现

    执行myForEach后会调用该方法的for循环,而每一次for循环则会调用其中的fn,

    此时则会执行我们在最后一个方法中写的:console.log("item:" + item + ",index:" + index + ",this:" + arr);

    提问:若在for循环之后再加一个fn(),会发生什么?

  • 相关阅读:
    解决JDBC连接MySQL 8时得异常:java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.
    洛谷P2604(最大流+最小费用最大流)
    poj2411(状压dp)
    二轮前水题计划
    最近挖的坑
    关于我
    future
    mysql学习笔记
    vue踩坑记
    XSS漏洞学习笔记
  • 原文地址:https://www.cnblogs.com/axu1997/p/11839236.html
Copyright © 2020-2023  润新知