简体   繁体   中英

Eloquent Javascript Chapter 5 Exercise 1

The challenge was to take a simple array:

var arrays = [[1,2,3],[4,5],[6]];

And use reduce/concat to create a single array containing all values and log to the console ie [1,2,3,4,5,6] so I produced:

console.log(arrays.reduce(function(flat, current) {
  return flat.concat(current);
}));

Totally works but on checking their solution they have one little difference:

console.log(arrays.reduce(function(flat, current) {
  return flat.concat(current);
}, []));

What does the [ ] parameter do in the reduce function, and is it a problem that I left it out?

reduce has the option of being passed an initial value. In their solution, they provide an empty array so the rest of your values can be added from there.

However, yours works because reduce uses the first value in the array as the initial value if one isn't given.

From MDN (note that previousValue is the first argument in the callback, currentValue is the second argument):

The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

Initial value.

The difference appears in two cases:

  • You version will crash if arrays is empty array. Theirs won't.

  • If arrays contains the single array, you get that instance, but they copy it into a new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM