【问题标题】:Why `array.reduce()` starts from index 1为什么`array.reduce()`从索引1开始
【发布时间】:2019-09-05 02:21:55
【问题描述】:

我想知道为什么array.reduce() 中的索引在下面的示例中从 1 而不是 0 开始

([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11

【问题讨论】:

  • 如果不传递第二个参数,它会从元素 1 开始,并将元素 0 作为累加器值传递。

标签: javascript ecmascript-6


【解决方案1】:

如果您不将值作为第二个参数传递,则累加器将采用第一个值:

// add a vlaue to start
([11,22,33,44]).reduce((acc, val, index) => console.log(val), 0);
// now all values are iterated

如果你记录累加器,你可以看到所有值在没有第二个参数的情况下是如何使用的:

// Show accumulator return value
let final = ([11,22,33,44]).reduce((acc, val, index) => (console.log("acc:", acc, "val:", val), val));

// final is the last object that would have been the accumulator
console.log("final:", final)

【讨论】:

    【解决方案2】:

    因为.reduce 被设计为在没有初始累加器的情况下工作:

        [1, 2, 3].reduce((a, b) => a + b)
    

    为此,a 将是第一个元素,b 在第一次迭代中是第二个元素,下一个将采用前一个结果和第三个值。

    如果您将初始累加器作为第二个参数传递,它将从索引 0 开始。

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 1970-01-01
      • 2013-01-01
      • 2011-11-11
      • 1970-01-01
      • 2019-09-05
      • 2013-05-29
      • 2016-12-27
      相关资源
      最近更新 更多