本文已参与「新人创作礼」活动,一起开启掘金创作之路。
Array.prototype.reduce() 和 Array.prototype.map() 是常用的数组方法,这篇文章主要对这两个方法进行介绍和一些使用例子,并自己实现一下这两个方法。
首先应该了解一下 reduce 和 map 的概念。
reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 方法不包括数组中被删除或从未被赋值的元素
| 参数 | 描述 | ||
|---|---|---|---|
| function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 函数参数: | 参数 | 描述 |
| total | 必需。初始值, 或者计算结束后的返回值。 | ||
| currentValue | 必需。当前元素 | ||
| currentIndex | 可选。当前元素的索引 | ||
| arr | 可选。当前元素所属的数组对象。 | ||
| initialValue | 可选。传递给函数的初始值- 如果没有提供 initialValue,那么第一次调用 callback 函数时,total 使用原数组中的第一个元素,currentValue 即是数组中的第二个元素。 在没有初始值的空数组上调用 reduce 将报错。 |
- 如果提供了 initialValue,那么将作为第一次调用
callback函数时的第一个参数的值,即 total,currentValue 使用原数组中的第一个元素。
没指定 initialValue
let arr = [1, 2, 3];
let res = arr.reduce((pre, cur, index, arr) => {
return pre + cur;
});
console.log(res); // 输出 6 (1 + 2 + 3)
指定 initialValue
let arr = [1, 2, 3];
let res = arr.reduce((pre, cur, index, arr) => {
return pre + cur;
},4);
console.log(res); // 输出 10 (4 + 1 + 2 + 3)
map
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法不包括数组中被删除或从未被赋值的元素
| 参数 | 描述 | ||
|---|---|---|---|
| function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数: | 参数 | 描述 |
| currentValue | 必须。当前元素的值 | ||
| index | 可选。当前元素的索引值 | ||
| arr | 可选。当前元素属于的数组对象 | ||
| thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。 |
let arr = [1, 2, 3];
let arr1 = arr.map((cur, index, arr) => {
return cur * 2;
});
console.log(arr1); // [2, 4, 6]
使用 map 定义二维数组(一定要用 fill 填充数组,否则 map 会跳过)
let arr = new Array(10).fill(0).map(() => {return new Array(10).fill(0);});
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;
}
实现 reduce
// 接受参数与 Array.reduce 应一样
Array.prototype.myReduce = function(fn, initValue) {
let arr = this;
let pre = initValue || 0;
for (let i = 0; i < arr.length; ++i) {
pre = fn.call(null, pre, arr[i], i, arr);
}
return pre;
}
最后
欢迎大家在评论区一起交流,一起进步!