lgwebdream / FE-Interview

🔥🔥🔥 前端面试,独有前端面试题详解,前端面试刷题必备,1000+前端面试真题,Html、Css、JavaScript、Vue、React、Node、TypeScript、Webpack、算法、网络与安全、浏览器
https://lgwebdream.github.io/FE-Interview/
Other
6.82k stars 896 forks source link

Day226:用 reduce 实现 map 方法 #1045

Open Genzhen opened 3 years ago

Genzhen commented 3 years ago

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案 欢迎大家在下方发表自己的优质见解 二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。


reduce & map

reduce 是一个累加方法,是对数组累积执行回调函数,返回最终计算的结果。

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

map 是遍历数组的每一项,并执行回调函数的操作,返回一个对每一项进行操作后的新数组。

array.map(function (crrentValue, index, arr) {}, thisArg);
Array.prototype.myMap = function (fn, thisArg = []) {
  if(typeof fn !== function){
      throw new Error(`${fn} is not a function`);
  }
return this.reduce((pre, cur, index, arr) => {
    return pre.concat(fn.call(thisArg, cur, index, arr));
  }, []);
};
var arr = [2, 3, 1, 5];
arr.myMap(function (item, index, arr) {
  console.log(item, index, arr);
});
let res = arr.myMap((v) => v * 2);
console.log(res); // [4,6,2,10]
chensiguo commented 3 years ago
return this.reduce((pre, cur, index, arr) => {
    return pre.concat(fn.call(thisArg, cur, index, arr));
  }, []);;

这样会不会更好呢