手动实现reduce函数

reduce 函数 可以自动将数组求和,但它内部是如何实现的呢? 今天我们来自己实现一个 reduce 函数

reducer 作用

数组求和

1
2
3
4
5
let arr = [1, 2, 3, 4];
arr.reduce((count, num) => {
return count + num;
});
// 10

数组求乘积

1
2
3
4
5
let arr = [1, 2, 3, 4];
arr.reduce((count, num) => {
return count * num;
});
// 24

数组求最大(小)值

1
2
3
4
5
6
7
8
9
let arr = [1, 2, 3, 4];
arr.reduce((count, num) => {
return count > num ? count : num;
});
// 4
arr.reduce((count, num) => {
return count < num ? count : num;
});
// 1

当然 还有其他的使用方法

编码实现

1
2
3
4
5
6
7
8
9
10
11
Array.prototype.myreduce = function (backcall, grandTotal = 0) {
if (typeof backcall !== 'function') {
throw new TypeError(
`${Object.prototype.toString.call(backcall)} is not a function`
);
}
for (let index = 0; index < this.length; index++) {
grandTotal = backcall(grandTotal, this[index], index, this);
}
return grandTotal;
};
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%