[英]Understanding how the reduce() function works
I am just ensuring that I know how this function works. 我只是确保我知道此功能的工作原理。 I read material and watched videos on the reduce function for probably 3 hours last night, I did not get it.
昨晚我阅读了资料并观看了关于reduce功能的视频,大概持续了3个小时,但我还是没听懂。 I stepped away from my computer, made some food, watched a TV show, and then looked at the computer again and BAM!
我离开电脑,吃东西,看电视节目,然后又看着电脑和BAM! I got it.
我知道了。 I know how the reduce function works now.
我知道reduce函数现在如何工作。
I just don't know why the first example below works while the second doesn't. 我只是不知道为什么下面的第一个示例有效,而第二个示例却无效。
source: Eloquent Javascript Ch. 资料来源: 雄辩的Javascript Ch。 5 §Flattening
5§平整
This works: 这有效:
var arrays = [[1, 2, 3], [4, 5], [6]];
var flattened = arrays.reduce(function(a, b) {
return a.concat(b);
});
flattened; //=>[1, 2, 3, 4, 5, 6]
I tried to fiddle around with the code, to change the variable to a function. 我试图弄乱代码,将变量更改为函数。 And somehow, I broke it.
而且以某种方式,我打破了它。 This below returns
undefined
, and I am not sure why. 以下返回
undefined
,我不确定为什么。
This doesn't work: 这不起作用:
var arrays = [[1, 2, 3], [4, 5], [6]];
function flattened(arr){
arr.reduce(function(a, b) {
return a.concat(b);
});
}
flattened(arrays); //=> undefined
Why does the first function work, but not the second? 为什么第一个功能起作用,而第二个功能却不起作用? I'm sure it's something small I am missing.
我确定这是我所想不到的小东西。
You need to return
from the flattened
function. 您需要从
flattened
函数return
。
function flattened(arr){
return arr.reduce(function(a, b) {
return a.concat(b);
});
}
Because the function flattened
doesn't return anything. 因为
flattened
的函数不会返回任何内容。
function flattened(arr){
/* “return” needs to be here */ arr.reduce(function(a, b) { // No return from the outer wrapper function “flattened”
return a.concat(b); // return from the inner function “reduce”
});
}
The function within it does return something, but the containing function doesn't. 其中的函数确实返回某些内容,但包含的函数没有返回结果。
The flattened() needs to return the value like this: flattened()需要返回如下值:
var arrays = [[1, 2, 3], [4, 5], [6]];
function flattened(arr){
return arr.reduce(function(a, b) {
return a.concat(b);
});
}
flattened(arrays);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.