Implementation principle of forEach in JavaScript (simple implementation steps)

Create a new array object arr:

var arr = ['xiaoming','lihua']

Add a method for_Each to arr:

arr.for_Each = function (fn) {
    for (var i = 0; i < this.length; i++) {
        fn(this[i])
    }
}

Call the for_Each method:

arr.for_Each((item) => {
    console.log(item)
})

Output result:

When arr calls the for_Each method, this points to arr itself, for_Each is passed to the function fn, and then each item of arr is passed to the fn function.

The for_Each method is often written into the prototype to facilitate the call of all array objects. The overall code is as follows:

var arr = ['xiaoming', 'lihua']
Array.prototype.for_Each = function (fn) {
    for (var i = 0; i < this.length; i++) {
        fn(this[i])
    }
}
arr.for_Each((item) => {
    console.log(item)
})

 

Guess you like

Origin blog.csdn.net/qq_41999592/article/details/104393097