Array.prototype.myReduce = function (fn, initValue) {
let arr = Array.prototype.slice.call(this)
if (!arr.length) {
return
}
let pre = initValue || arr[0]
let startIndex = initValue ? 0 : 1
for (; startIndex < arr.length; startIndex++) {
pre = fn(pre, arr[startIndex], startIndex, arr)
}
return pre
}
const arr = [2, 30]
const max = arr.myReduce((pre, cur, index, a1) => Math.max(pre, cur), -Infinity)
console.log(max) //30
Javascript handwriting redefines array reduce
Guess you like
Origin blog.csdn.net/qq_38902432/article/details/130899933
Recommended
Ranking