Array.prototype.newReduce=function(fn, value){const currentArr =this;// 如果一个空数组而且没有传入初始值则报错if(currentArr.length ==0&& value == undefined){throw("Reduce of empty array with no initial value");}// 判断value是否有传入, 没有传入则默认使用数组中的第一个元素if(value !== undefined){// 如果有传入, 则需要从数组的第0项开始遍历for(let i =0; i < currentArr.length; i++){// reduce函数可以传入四个参数, // 第一个参数为上次调用的累计值// 第二个参数为当前值// 第三个参数为当前值的索引// 第四个参数为数组本身
value =fn(value, currentArr[i], i, currentArr)}}else{// 如果没有传入则默认使用数组中第一个元素作为pre, 并且从数组的第1项开始遍历
value = currentArr[0];for(let i =1; i < currentArr.length; i++){
value =fn(value, currentArr[i], i, currentArr)}}return value;}// 测试let arr =[1,2,3,4];
console.log(arr.newReduce(function(pre, cur, index, arr){return pre + cur
}));// 10