Handwritten implementation of an Array.map

Let’s implement a simple map method today

First, let's take a look at the use of the map method and the specific parameters

 

        var arr = ["a","b","c","d","e"];
        arr.map(function(currentValue,index,arr){
            console.log("current element"+ currentValue )
       console.log("current index"+index)
            console.log("array object"+arr)
        })

The parameters of the map:

            currentValue   is required . the value of the current element

            index   is optional . The index value of the current element

            arr   is optional . the array object to which the current element belongs

 

Let's think about it first, directly Array.map() can call the map method, then it should be on the prototype chain, and then receive an anonymous function as a parameter, and call the incoming anonymous function through a loop

Let's try to write

 

    Array.prototype.newMap = function(fn) {

      var newArr = [];

      for(var i = 0; i<this.length; i++){

        newArr.push(fn(this[i],i,this))

        }

      return newArr;

      }

 

Come on, call and try

        arr.newMap((currentValue,index,arr)=>{
            console.log("newMap current element"+currentValue)
       console.log("newMap current index"+index)
            console.log("newMap array object"+arr)
        })
 Array.prototype.newMap = function(fn) {
    var newArr = [];
    for(var i = 0; i<this.length; i++){
      newArr.push(fn(this[i],i,this))
    }
    return newArr;
 }
 var arr = [3, 4, 5];
 var newArr = arr.newMap(function(item, index, arr) {
 	console.log(item, index, arr);
 });
 console.log(newArr);
//3 0 [3, 4, 5]
//4 1 [3, 4, 5]
//10 5 [3, 4, 5]
//[undefined, undefined, undefined]

  Reference: https://www.cnblogs.com/suihang/p/10535002.html

Guess you like

Origin blog.csdn.net/weixin_42693104/article/details/117672312