reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。对空数组是不会执行回调函数的。
Array.prototype.myReduce = function (fun, value = 0) {
for (const item of this) {
value = fun(item, value)
}
return value
}
const arr = [1, 3, 5, 7, 9]
const func = function (a, b) {
return a + b
}
const res = arr.myReduce(func)
console.log(res) // 25