js 手写 map 函数

一 map 函数(copyMap)

map函数接收两个参数

1 迭代器函数 ,该函数有三个参数

  • 数组项的值
  • 数组项下标
  • 数组对象本身

2 迭代器函数的this指向
(注:当传了该值,迭代器函数不能为箭头函数了。原因是箭头函数没有this隐式指向。箭头函数在定义时候就已经绑定了上层上下文中非箭头函数this)

Array.prototype.copyMap = function (fn, toThis) {
  let arr = this;
  const result = [];
  const redirectThis = toThis || Object.create(null);
  for (let i = 0; i < arr.length; i++) {
    const item = fn.call(redirectThis, arr[i], i, arr);
    result.push(item);
  }
  return result;
};
原文地址:https://www.cnblogs.com/honkerzh/p/14088828.html