当前位置: 代码迷 >> 综合 >> 手写数组的 reduce 函数
  详细解决方案

手写数组的 reduce 函数

热度:97   发布时间:2024-01-10 19:09:16.0

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