Array.forEach principle, copy a similar function

Array.forEach principle, copy a similar function

array.forEach

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

Above

We use the forEach can traverse an array, and remove its index, item, as well as the array itself

Then based on the value returned can achieve what you want features such sum

principle

The principle of this function is to use the Array prototype object of the operation, the following examples are based on this principle of imitation forEach, in order to explain the principles of the method

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

That is, when we are called once myForEach function, which will be called fn this.length-1 times (where this was referring to the object of the method call)

Run the following code can be found in accordance with the output does 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);
    })

When we break point in arr.muForEach (function (item, index, arr)) .. this line, and then step by step debugging can be found in the debugging stage

This method is called for loop after executing myForEach, and each time the for loop will call them fn,

At this point we write will be executed in the final process: console.log ( "item:" + item + ", index:" + index + ", this:" + arr);

Question: If a plus fn after the for loop (), what happens?

Guess you like

Origin www.cnblogs.com/axu1997/p/11839236.html