Javascript handwriting redefines array reduce

 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

Guess you like

Origin blog.csdn.net/qq_38902432/article/details/130899933