首页 > 技术文章 > JS 手写之 Array.prototype.map

frank-link 2021-05-21 07:59 原文

Array.prototype.map

map() 方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。

语法

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

参数

  • callback - 生成新数组元素的函数,使用三个参数:
    • currentValue - callback 数组中正在处理的当前元素
    • index - 可选,callback 数组中正在处理的当前元素的索引
    • array - 可选,map 方法调用的数组
  • thisArg - 可选,执行 callback 函数时值被用作 this。

返回值

一个由原数组每个元素执行回调函数的结果组成的新数组。

Array.prototype.myMap

Array.prototype.myMap = function (callbackFn, thisArg) {
  // 处理回调类型异常
  if (Object.prototype.toString.call(callbackFn) != "[object Function]") {
    throw new TypeError(callbackFn + " is not a function");
  }
  var res = [];
  for (var i = 0, len = this.length; i < len; i++) {
    res.push(callbackFn.call(thisArg, this[i], i, this));
  }
  return res;
};

测试

const arr = [1, 2, 3, 4];

const a = arr.myMap((item, index) => item + index);
console.log(a); // [1, 3, 5, 7]

arr.myMap("555"); // Uncaught TypeError: 555 is not a function

推荐阅读