ES6中Array.protype.reduce 的使用以及源码

2020-05-11  本文已影响0人  泰然自若_750f

Array.protype.reduce

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

应用1:数组求和

let d=[1,2,3,4,5];
var res=d.reduce((a,b)=>{
      return a+b;
}.2); //13

源码实现

Array.prototype._reduce=function(cb,defaultValue){
  //  debugger
    if(!Array.isArray(this))
    {
        throw new TypeError('this is not array');
    }
     
    if(typeof cb!=='function')
    {
        throw new TypeError('no function');
    }
    if(this.length<2)
    {
        return defaultValue?defaultValue:null;
    }
 
    let arr=[...this],res=null;
    //没有初始值 取第一个,数组长度也会减少1
 res=defaultValue?defaultValue.shift();
    //依次执行
    arr.map((item,index)=>res=cb(res,item,index,arr));
    return res;
}
let d=[1,2,3,4,5]
d._reduce((a,b)=>{
      return a+b;
})
//11
上一篇 下一篇

猜你喜欢

热点阅读