目录
引言
js 的数据结构里数组 Array 无疑是最重要的部分之一,包含很多方法属性各有用途,假如用它们互相实现,相信是件很有趣的事儿。用reduce 实现map之前先得了解 reduce 和 map 方法。
reduce方法
作用:对数组中的每个元素按序执行传入的回调函数,每一次运行回调会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。简而言之,就是求和。
reduce(function callback (previousValue, currentValue, currentIndex, array) {}
, initialValue)
可以看到 reduce方法传入俩个参数:回调函数和初始值;
回调函数可传四个参数:上次回调函数的返回值(initialValue/array[0])、数组中当前处理的元素、当前处理的元素的索引、用于遍历的数组。
initialValue(可选),作为第一次调用 callback
函数时参数 previousValue 的值。若指定了初始值 initialValue
,则 currentValue
则将使用数组第一个元素;否则 previousValue
将使用数组第一个元素,而 currentValue
将使用数组第二个元素。
map方法
作用:创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的回调函数后的返回值组成,并返回新数组。map() 的初衷是不修改调用它的原数组本身(当然可以在 callback
执行时改变原数组)
语法:Array.prototype.map()
map(function callback(currentValue, currentIndex, array) {}
, thisArg)
可以看到 map方法传入俩个参数:回调函数 和 被用作执行回调函数的this
;
回调函数可传三个参数:数组中当前处理的元素、当前处理的元素的索引、用于遍历的数组。
thisArg
表示执行回调函数callback()时的this指向。可选参数。当不写时,则默认是指向window全局。
reduce实现map
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)); 此处等价下面俩行
pre.push(fn.call(thisArg, cur, index, arr));
return pre
}, [])
}
const arr = [1, 2, 3];
console.log(arr.myMap(item => item * 2)); // 2 4 6
reduce 实现 map 、filter
const numbers = [-1, 3, 0, 2];
const fun = numbers.reduce((previousValue, currentValue) => {
if (currentValue > 0) {
const doubled = currentValue * 2;
previousValue.push(doubled);
}
return previousValue;
}, []);
console.log(fun); // [6, 4]