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

相关推荐

2024-12-30 22:31
吉首大学 Web前端
工字钢写代码:改成吉林就OK了
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务