一. 定义

**map()**方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

二. 用法

**map()** 方法按照原始数组元素顺序依次处理元素。
注意:

  • **map()** 不会对空数组进行检测。
  • **map()** 不会改变原始数组。

    三. 手写代码

    1. Array.prototype.newMap = function (fn) {
    2. let arr = this;
    3. let result = [];
    4. for(let i=0; i<arr.length; i++){
    5. result[i] = fn(arr[i]);
    6. }
    7. return result;
    8. }

    四. 测试代码

    1. const arr = [1, 2, 3, 4];
    2. console.log(arr.map(item => item*2)); // [ 2, 4, 6, 8 ]
    3. console.log(arr.newMap(item => item*2)); // [ 2, 4, 6, 8 ]