了解 .reduce() 中的许多函数参数

Understanding the many function parameters in .reduce()

下面的 .reduce() 方法取自 ,包含许多参数(表面上称为 解构对象)。

这些参数代表什么功能?

let {result} = array.reduce(({arg_1, arg_2, arg_3}, arg_4)=> {
}, {result: [], arg_2: 0, arg_3: undefined})
return result

Array.reduce需要2个参数,

  1. 回调
  2. 初始值

Array.reduce的回调有4个参数:

  1. 上一个值
  2. 当前值
  3. 当前索引
  4. 数组

previousValue 的值在循环开始时为 initialValue。如果没有传递任何值,第一个元素将被视为previousValue并且currentValue将具有下一个值。从他们那里,previousValue 将保留上一次迭代返回的值。

样本

无初始值

var a = [1,2,4,4,5,6,7,8];

a.reduce(function(p,c,i,a){
  console.log(p,c,i,a);
  return c
})

有初始值

var a = [1,2,4,4,5,6,7,8];

a.reduce(function(p,c,i,a){
  console.log(p,c,i,a);
  return c
},0)

参考

Array.reduce

如果 OP 在解构符号上绊倒了,对于给定的示例,第一个参数是初始值(用前两个注释的 provided links 描述),用作收集器或累加器对象。它由另一个方法的前三个参数组成。结果由解构赋值写入,因此,将有 3 个变量,arg_1arg_2arg_3 来自最终返回的收集器对象的同名参数。

edit, for the OP's provided example code has changed ...

下一个示例考虑了 OP 的链接 SO 代码参考...

let {slots} = array.reduce(({slots, count, prev}, item)=> {

    // ... do something with slots
    // ...
    // while iterating always needs to return
    // an equally structured collector object

    return {slots, count: count + 1, prev: item}

}, {slots: [], count: 0, prev: undefined})

/*
return slots; // does not really make sense within this shortened example's context.
*/

...等于...

var slots = array.reduce(function (collector, item) {

    var
        slots = collector.slots,
        count = collector.count,
        prev  = collector.prev;

    // ... do something with slots
    // ...
    // while iterating always needs to return
    // an equally structured collector object

    return {slots: slots, count: count + 1, prev: item};

}, {slots: [], count: 0, prev: undefined}).slots;

reduce 方法接受两个参数。

语法:

arr.reduce(callback[, initialValue])

因此,在您的示例中,回调用作第一个参数 arrow function。让我们打破它:

1. ({arg_1, arg_2, arg_3}, arg_4)=> {}  //the callback
2. {arg_1: [], arg_2: 0, arg_3: undefined} // the initial value

并且 ({arg_1, arg_2, arg_3}, arg_4) 两个 个参数用于 arrow function,第一个被声明为对象。

您会注意到 arg_4 的初始值丢失了。