在JavaScript中定义参数
我正在查看JavaScript中的reduce函数在JavaScript中定义参数,javascript,parameters,reduce,Javascript,Parameters,Reduce,我正在查看JavaScript中的reduce函数 var colors = ['red', 'red', 'green', 'blue', 'green']; var distinctColors = colors.reduce( (distinct, color) => (distinct.indexOf(color) != -1) ? distinct : [...distinct, color],
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)
reduce()方法对累加器和每个累加器应用一个函数
数组中的元素(从左到右),以将其缩减为单个
价值
从
所以它只是一个累加器,或“当前状态”值。例如,让我们查找数组的最大值:
let值=[4,5,6,77,8,12,0,9];
设最大值=值。减少((acc,curr)=>{
log(`comparing${acc}和${curr}`);
返回数学最大值(acc,curr)
},0);
控制台日志(最大值)代码>首先来自快速描述:
reduce()方法对累加器和每个累加器应用一个函数
数组中的元素(从左到右),以将其缩减为单个
价值观
实际上:
arr.reduce(callback[,initialValue])
其中callback将(累加器,当前值)
作为参数。累加器是减少值的保留数组,currentValue是正在比较的当前数组索引的值
在您的示例中:
请参阅最后一部分,即,[]
-传递给reduce
的第二个参数是distinct
的类型-根据要用作回调第一次调用的第一个参数的文档:[可选]值。如果没有提供初始值,将使用数组中的第一个元素。在没有初始值的空数组上调用reduce是一个错误。-因此,传递给reduce函数的第二个参数是default,是的,我理解。但是回调函数如何假定distinct
是默认参数而不是color
?回调函数的第一个参数始终是默认值-它不会四处移动。
// 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, []);