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
本文详细解析了数组reduce()方法的工作原理,展示了如何通过自定义实现来加深对这一JavaScript核心功能的理解。通过实例演示,reduce()方法能将数组元素缩减为单一值,适用于求和、拼接等操作。
1950

被折叠的 条评论
为什么被折叠?



