The first day, guided learning to implement the map method of the array

The first day, guided learning to implement the map method of the array


This article simply wants to analyze how to implement the principle for some friends with poor basics.

1. First look at the rules of the function

The picture above is the specification of map

Two parameters:

  • The first parameter is the callbackfn callback function,

    • value is the current value traversed
    • index is the subscript traversed to the current
    • array is the original array to be traversed
  • The second parameter is thisArg : it is an arbitrary object. It is used to replace the pointer of this traversal function context.

Return value: array

Therefore, the meaning of the map function is to make a change to the entire attribute and return an array of the same length.

2. First look at the basic use of array map

let array1 = [ { a: 1 }, 2, 3, 4]
let obj = {}
let array2 = (item, index, arr) {
    console.log(this === obj)   //true
    if (typeof item === 'object') {
        item.a = 2
    return item
}, obj)

console.log(array1[0] === array2[0])    //true
  • Features:
    • array1 is not equal to array2.
    • If the element is a reference data type, it will be shallowly copied.

3. Realize map by handwriting

//1.  map  
Array.prototype.myMap = function(callbackfn, thisArg) {
    var newArray = []   // 
    //  copy 
    var currentArray = this.slice() // 
    //var currentArray =   
    //var currentArray = [...this]
    for(var i = 0; i < currentArray.length; i++) {
        //3.  thisArg  
        newArray.push(, currentArray[i], currentArray))
    return newArray

It's that simple.