JavaScript reduce中定义参数

4

我正在研究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中。但我不明白函数参数(distinct, color)是如何定义为空数组和每个颜色的。
JavaScript是否自动假定distinct是数组,因为我调用了distinct.indexOf(color)

2
看到最后一部分,那个,[] - 你传递给reduce的第二个参数是distinct的类型 - 根据文档:*[可选]作为回调函数第一次调用的第一个参数使用的值。如果没有提供初始值,则将使用数组中的第一个元素。在没有初始值的情况下对空数组进行reduce操作是错误的。* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce - tymeJV
第二个参数传递给reduce函数是默认值,我理解。但回调函数如何假定distinct是默认参数而不是color - Aran Freel
1
回调函数的第一个参数始终是默认值 - 它不会发生变化。 - tymeJV
2个回答

2
reduce()方法将一个函数应用于累加器和数组中的每个元素(从左到右),以将其减少为单个值。引自MDN
因此,它只是一个累加器或“当前状态”值。例如,让我们找到数组的最大值:

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);

这段代码只是在每一步中存储(累加)找到的最大值,然后将其返回。


2

首先是来自 MDN 的简要描述:

reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,以将其减少为单个值。

实际应用:

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, []);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接