# 手写实现 Array.reduce() #

Array.prototype.myReduce = function(callback, initialValue) {
  // 判断数组是否为空
  if (this.length === 0) {
    throw new TypeError('Reduce of empty array with no initial value');
  }

  // 判断是否提供了初始值,如果没有则将第一个元素作为初始值
  let accumulator = initialValue !== undefined ? initialValue : this[0];

  // 判断是否提供了初始值,如果没有则从索引 1 开始遍历
  let startIndex = initialValue !== undefined ? 0 : 1;

  // 遍历数组,对每个元素应用回调函数,并将结果累积到 accumulator 变量中
  for (let i = startIndex; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this);
  }

  return accumulator;
};

// 示例用法
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.myReduce((acc, curr) => acc + curr, 0); // 输出:15

全部评论
等级太低,表示看不懂
点赞 回复 分享
发布于 2023-07-28 17:20 广东

相关推荐

不愿透露姓名的神秘牛友
07-09 12:02
ssob上原来真有BOSS啊
硫蛋蛋:这种也是打工的,只不是是给写字楼房东打工
点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务