在 JavaScript 中定义参数 reduce

Defining Parameters in JavaScript reduce

我正在查看 JavaScript 中的这个 reduce 函数。 . .

var colors = ['red', 'red', 'green', 'blue', 'green'];

var distinctColors = colors.reduce(
    (distinct, color) =>
        (distinct.indexOf(color) != -1) ?
            distinct : 
            [...distinct, color],
    []
)

我理解回调函数对colors数组中的每一项调用一次,在distinct中搜索color字符串,如果找到则返回数组, 如果找不到,将 color 添加到 distinct

我不明白的是函数参数(distict, color)是如何定义为空数组和每种颜色的。

是否 JavaScript 自动假定 distinct 是数组,因为我调用 distinct.indexOf(color)

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. from MDN.

所以它只是一个累加器,或者一个 "current state" 值。例如,让我们找到一个数组的最大值:

let values=[4,5,6,77,8,12,0,9];

let max=values.reduce((acc,curr) => {
  console.log(`comparing ${acc} and ${curr}`); 
  return Math.max(acc,curr)
  },0);

console.log(max);

此代码只是存储(累加)在每一步中找到的最大值,然后 returns 它。

首先来自MDN的快速描述:

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

实际上:

arr.reduce(callback[, initialValue]) 其中回调将 (accumulator, currentValue) 作为参数。累加器是您减少的值的保存数组,currentValue 是您正在比较的当前数组索引的值。

在你的例子中:

// Reducer function, returns either the current state of the accumulator
// or returns a new array instance of the accumulator with the new value
const getDistinctColors = (accumulator, currentValue) => ((accumulator.indexOf(currentValue) !== -1) ? accumulator : [ ...accumulator, currentValue ]);
  
// define color group
let colors = ['red', 'red', 'green', 'blue', 'green'];
// reduce color group (initialize with empty array [])
let distinctColors = colors.reduce(getDistinctColors, []);