JavaScript 用reduce()方法实现map()方法
原生js实现,reduce实现map
Array.prototype.myMap = function (func) {
const arr = this;
return arr.reduce((pre, ele) => {
return [...pre, func(ele)];
}, []);
}
const arr = [1, 2, 3, 4, 5];
const newarr = arr.myMap((ele) => ele * 2);
console.log(arr); //[1,2,3,4,5]
console.log(newarr); //[2,4,6,8,10]