在JavaScript中定义参数reduce [英] Defining Parameters in JavaScript reduce
问题描述
我正在看JavaScript中的reduce函数. . .
I am looking at this reduce function in JavaScript . . .
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
(如果找不到).
I understand that the callback function is called once for each item in the colors
array, searching for the color
string in distinct
and simply returning the array if it is found, and adding color
to distinct
if not found.
我不明白的是函数参数(distict, color)
是如何定义为空数组和每种颜色的.
What I do not understand is how the function parameters (distict, color)
are defined as the empty array and each color.
JavaScript是否会自动假定distinct
是数组,因为我调用了distinct.indexOf(color)
??
Does JavaScript automatically assume that distinct
is the array because I call distinct.indexOf(color)
??
推荐答案
reduce()方法对一个累加器应用一个函数,每个累加器 数组中的元素(从左到右)以将其简化为单个 价值. 来自 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. from MDN.
因此,它只是一个累加器或当前状态"值.例如,让我们找到一个数组的最大值:
So it is just an accumulator, or a "current state" value. For example, let's find the maximum value of an array:
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);
此代码仅存储(累积)在每个步骤中找到的最大值,然后将其返回.
This code just stores (accumulates) the maximum value found in each step, and then returns it.
这篇关于在JavaScript中定义参数reduce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!