MDN上map的语法

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

参数分析

map方法接受一个回调函数,其参数如下

参数是否必须类型描述
currentValue可选callback 数组中正在处理的当前元素
index可选callback 数组中正在处理的当前元素的索引。
array可选map 方法调用的数组。

代码

Array.prototype.myMap = function (callback) {
  // 判断回调是不是一个函数
  if (typeof callback !== "function") {
    throw new Error(`Uncaught TypeError: ${callback} is not a function`); // 抛出异常
  }
  const result = [];
  for (let i = 0; i < this.length; i++) {
    result.push(callback(this[i], i, this));
  }
  return result;
};

延申到filter

我们都知道filter接受一个回调函数,这个回调函数返回一个Boolean,并且这个回调函数接受的参数和map方法一样,所以我们只要稍微修改一下这个方法就可以了

Array.prototype.myFilter = function (callback) {
  // 判断回调是不是一个函数
  if (typeof callback !== "function") {
    throw new Error(`Uncaught TypeError: ${callback} is not a function`); // 抛出异常
  }
  const result = [];
  for (let i = 0; i < this.length; i++) {
  	// 每次遍历调用一下callback来判断是否push进新的数组里面
    if (callback(this[i], i, this)) {
      result.push(this[i]);
    }
  }
  return result;
};