我正在查看 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.
所以它只是一个累加器,或“当前状态”值。例如,让我们找到一个数组的最大值:
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);
这段代码只是存储(累加)每一步找到的最大值,然后返回它。
关于javascript - 在 JavaScript reduce 中定义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45922864/