首先应该了解一下 reduce 和 map 的概念。
reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
参数 | 描述 | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 函数参数:
| ||||||||||
initialValue | 可选。传递给函数的初始值
|
map
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
| ||||||||
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。 |
reduce 实现 map
// 接受参数与 Array.map 应一样
Array.prototype.myMap = function(fn, thisValue) {
let arr = [];
// 同 map 的规则, thisValue传入null,则 this 指向全局对象
let thisV = thisValue || null;
this.reduce((total, currentValue, index, arr) => {
arr.push(fn.call(thisV, currentValue, index, arr));
}, null);
return arr;
}
let arr = [1, 2, 3];
arr.myMap((item) => { return item * 2}); // [2, 4, 6]