Skip to content

Commit a82dfee

Browse files
committed
feat: 完成手写reduce函数
1 parent 8cc2ee3 commit a82dfee

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

面试常见的手写题/15-reduce.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const arr = [1, 2, 3, 4, 5]
2+
3+
// reduce有两种情况,第一种是传入initData,这个时候从数组的第一项开始遍历,第二种是不传入,initData就是数组的第一项
4+
Array.prototype._reduce = function (fn, initData) {
5+
let res = initData !== 0 && initData ? initData : this[0]
6+
for (let i = initData ? 0 : 1; i < this.length; i++) {
7+
res = fn(res, this[i])
8+
}
9+
return res
10+
}
11+
12+
const newArr = arr._reduce((initData, currentData) => {
13+
return initData + currentData
14+
}, 5)
15+
16+
console.log(newArr)

0 commit comments

Comments
 (0)