reduce方法是JavaScript中的一个高阶函数,它接收两个参数:一个回调函数和一个初始值。它的作用是进行累加操作,将数组中的每一个元素和初始值一起传入回调函数进行计算,得到单个的结果。然后将这个结果作为下一次计算的初始值,将下一个元素作为计算参数,重复调用回调函数进行计算。最终将每次计算得到的结果合成并返回一个单一的结果值。reduce方法可以用于数值、字符串、对象等类型数组,并且可以根据需要编写不同的回调函数来实现不同的功能
reduce核心代码
// myReduce
Array.prototype.myReduce = function (fn,...args) {
if(!arguments.length){
throw new error;
}
let pre = args.length>0? args[0] : this[0];
let startIndex = args.length>0?0:1;
for(let i = startIndex;i<this.length; i++) {
pre = fn(pre,this[i],i,this)
}
return pre
}