简体   繁体   English

雄辩的Javascript第5章练习1

[英]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: 并使用reduce / concat创建一个包含所有值的单个数组并登录到控制台即[1,2,3,4,5,6]所以我制作了:

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函数中做了什么,是不是我把它遗漏了?

reduce has the option of being passed an initial value. reduce可以选择传递初始值。 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. 但是,您的工作原理是因为reduce使用数组中的第一个值作为初始值(如果没有给出)。

From MDN (note that previousValue is the first argument in the callback, currentValue is the second argument): MDN (请注意, previousValue是回调中的第一个参数, currentValue是第二个参数):

The first time the callback is called, previousValue and currentValue can be one of two values. 第一次调用回调时, previousValuecurrentValue可以是两个值之一。 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. 如果在reduce的调用中提供了initialValue ,则previousValue将等于initialValuecurrentValue将等于数组中的第一个值。 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. 如果没有提供initialValue ,那么previousValue将等于数组中的第一个值, currentValue将等于第二个值。

Initial value. 初始值。

The difference appears in two cases: 差异出现在两种情况中:

  • You version will crash if arrays is empty array. 如果arrays是空数组,您的版本将崩溃。 Theirs won't. 他们不会。

  • If arrays contains the single array, you get that instance, but they copy it into a new one. 如果arrays包含单个数组,则会获得该实例,但会将其复制到新实例中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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