Defining Parameters in JavaScript reduce

冷暖自知 提交于 2019-12-11 03:43:53

问题


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

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.

What I do not understand is how the function parameters (distict, color) are defined as the empty array and each color.

Does JavaScript automatically assume that distinct is the array because I call distinct.indexOf(color)??


回答1:


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.




回答2:


First from MDN a quick description:

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.

Practically:

arr.reduce(callback[, initialValue]) where callback takes (accumulator, currentValue) as arguments. The accumulator is the holding array for your reduced values, currentValue is the value of the current array index you are comparing.

In your example:

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


来源:https://stackoverflow.com/questions/45922864/defining-parameters-in-javascript-reduce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!