zoukankan      html  css  js  c++  java
  • 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(),会发生什么?

  • 相关阅读:
    Spring Junit 读取WEB-INF下的配置文件
    cron表达式详解
    jQuery.Validate验证库
    CentOS6.x升级MySQL版本5.1到5.6
    Linux下部署
    jQuery插件之ajaxFileUpload
    javascript深入理解js闭包
    STM32常用参考资料
    STM32点灯需要的文件
    【编程1】写一个函数判断系统是大端还是小端
  • 原文地址:https://www.cnblogs.com/axu1997/p/11839236.html
Copyright © 2011-2022 走看看