What is the concept of Array.map?

前端 未结 8 1811
甜味超标
甜味超标 2020-11-30 06:36

I am having problems understanding the concept of Array.map. I did go to Mozilla and Tutorials Point, but they provided very limited info regarding this.

<
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 07:36

    Summary

    Array.map is a function which is located on Array.prototype.map. The function does the following:

    1. Creates a new array with the same amount of entries/elements.
    2. Executes a callback function, this function receives and current array element as an argument and returns the entry for the new array.
    3. Returns the newly created array.

    Example:

    Basic usage:

    const array = [1, 2, 3, 4];
    
    // receive each element of array then multiply it times two
    // map returns a new array
    const map = array.map(x => x * 2);
    
    console.log(map);

    The callback function also exposes an index and the original array:

    const array = [1, 2, 3, 4];
    
    // the callback function can also receive the index and the 
    // original array on which map was called upon
    const map = array.map((x, index, array) => {
      console.log(index);
      console.log(array);
      return x + index;
    });
    
    console.log(map);

提交回复
热议问题