我正在研究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)
?
,[]
- 你传递给reduce
的第二个参数是distinct
的类型 - 根据文档:*[可选]作为回调函数第一次调用的第一个参数使用的值。如果没有提供初始值,则将使用数组中的第一个元素。在没有初始值的情况下对空数组进行reduce操作是错误的。* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce - tymeJVdistinct
是默认参数而不是color
? - Aran Freel