# 题目描述

请你用 reduce 来实现 map

# 思路

reduce是一个累积方法,对数组累积执行回调函数

array.reduce(function (total, currentValue, currentIndex, arr) {}, initialValue)

  • total 必需。初始值, 或者计算结束后的返回值。
  • currentValue 必需。当前元素
  • currentIndex 可选。当前元素的索引
  • arr 可选。当前元素所属的数组对象。
  • initialValue可选。传递给函数的初始值 —— 这里我们要设置,如果不设置的话会用第一个元素当做初始值,导致我们少计算一个元素

map就是 遍历数组的 每一项 同时执行回调

array.map(function(currentValue,index,arr), thisArg)

  • currentValue 必须。当前元素的值
  • index 可选。当前元素的索引值
  • arr 可选。当前元素属于的数组对象
  • thisArg 可选。对象作为该执行回调时使用,传递给函数,用作 this 的值。
  • 如果省略了 thisArg,或者传入 null、undefined,那么回调函数的 this 为全局对象。

既然reduce是累加,我们就不能累加值,而是累加往数组中push的操作,每次push到res一个新的值

# 代码实现

Array.prototype.myMap = function (fn, thisArg) {
  var res = [];

  thisArg = thisArg || [];

  this.reduce(function (pre, cur, index, arr) {
    // res.push(fn(cur));
    res.push(fn.call(thisArg, cur, index, arr));
    // console.log("res: ", res);
  }, []);

  return res;
};

var arr = [2, 3, 1, 5];
let res = arr.myMap((i) => i * 2);

console.log("res: ", res);

// res:  [ 4, 6, 2, 10 ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20