[英]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
andcurrentValue
can be one of two values.第一次调用回调时,
previousValue
和currentValue
可以是两个值之一。 IfinitialValue
is provided in the call to reduce, thenpreviousValue
will be equal toinitialValue
andcurrentValue
will be equal to the first value in the array.如果在reduce的调用中提供了
initialValue
,则previousValue
将等于initialValue
,currentValue
将等于数组中的第一个值。 If noinitialValue
was provided, thenpreviousValue
will be equal to the first value in the array andcurrentValue
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.