0%

原理

先看看 reducemap 的使用方法

1
2
let new_array = arr.map(function callback(currentValue[, index[,array) {/* Return element for new_array */ }[, thisArg])
let result = arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

实现

第一种用 for 实现

1
2
3
4
5
6
7
Array.prototype.myMap = function(callback, thisArg) {
let arr = [];
for (let i = 0; i < this.length; i++) {
arr.push(callback.call(thisArg, this[i], i, this));
}
return arr;
};

第二种用 reduce 实现

1
2
3
4
5
6
7
Array.prototype.myMap = function(callback, thisArg) {
let result = this.reduce((accumulator, currentValue, index, array) => {
accumulator.push(callback.call(thisArg, currentValue, index, array));
return accumulator;
}, []);
return result;
};