reduce & map
reduce是一個累加方法,是對數組累積執行回調函數,返回最終計算的結果。
array.reduce(function (total, currentValue, currentIndex, arr) {},
initialValue);
1.total 必需:初始值,或者計算結束後返回的值
2.curentValue 必需:當前元素
3.currentIndex可選:當前元素的索引。
4.arr可選,當前元素的所屬的數組對象
5.initialvalue可選:傳給函數的初始值
map是遍歷數組的每一項,並執行回調函數的操作,返回一個對每一項進行操作後的新數組。
array.map(function (crrentValue, index, arr) {}, thisArg);
1.currentValue必需:當前元素只
2.index可選:當前元素索引值
3.arr可選:當前元素所屬數組對象
4.thisArg 可選:對象作為該執行回調時使用,傳遞給函數,用作 "this」的值。如果省略了thisArg,或者傳入null、undefined,那麼回調函數的this 為全局對象。
參考實現
Array.prototype.myMap = function (fn, thisArg = []) {
if(typeof fn !== function){
throw new Error(`${fn} is not a function`);
}
const res = [];
this.reduce((pre, cur, index, arr) => {
res.push(fn.call(thisArg, cur, index, arr));
}, []);
return res;
};
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]