# 手写实现 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 广东

相关推荐

已注销:再接着投吧项目经历太流水账,且没有实习经历,我之前也是这样,后来跟着大厂导师修改了项目和简历之后成功上岸,有需要可以问我
点赞 评论 收藏
分享
头像
08-05 15:59
已编辑
门头沟学院 运维工程师
哈哈哈,你是老六:感觉这女的就是把你当免费的劳动力
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

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