美文网首页
ES6中Array.protype.reduce 的使用以及源码

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

作者: 泰然自若_750f | 来源:发表于2020-05-11 17:03 被阅读0次

Array.protype.reduce

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

  • callback
    执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:
    1. accumulator
      累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。
    2. currentValue
      数组中正在处理的元素。
    3. index 可选
      数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。
    4. array可选
      调用reduce()的数组
  • initialValue(可选)
    作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。
    文档链接
    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

应用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

相关文章

网友评论

      本文标题:ES6中Array.protype.reduce 的使用以及源码

      本文链接:https://www.haomeiwen.com/subject/boaunhtx.html