FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

reduce 函数的功能,如何实现的,动手实现一下

Open lgwebdream opened this issue 5 years ago • 4 comments

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream


  const reduce = (source, callback, initValue) => {
    let acc = initValue;

    for (let index = 0; index < source.length; index++) {
      acc = callback(acc, source[index], index, source);
    }

    return acc;
  };

gaohan1994 avatar May 03 '24 05:05 gaohan1994

 Array.prototype.myreduce=function(fn,initial) {
        let st=0
       if(typeof initial==='undefined'){
        st=1
        initial=this[0]
       }
        for(let i=st;i<this.length;i++) {
            
     initial=fn(initial,this[i],i,this)
        }
        return initial

       }

       let arr=[1,2,3,4]
       let z=arr.myreduce((pre,cur)=>pre+cur)
       console.log(z)

Alicca-miao avatar Sep 30 '24 11:09 Alicca-miao

Array.prototype.myReducer = function (fn, initialValue) {
  const arr = this;

  let prev = initialValue;

  arr.forEach(item => {
    prev = fn(prev, item);
  });

  return prev;
}

ZhangDaZongWei avatar Oct 09 '24 00:10 ZhangDaZongWei