关于高阶函数的 Eloquent Javascript 章节,我来到了这个例子:
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;
}
console.log(reduce([1, 2, 3, 4], function(a, b) {
return a + b;
}, 0));
// → 10
当for
循环被重写为包含时,我认为是可选的,花括号,如:
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++) {
current = combine(current, array[i]);
return current;
}
}
console.log(reduce([1, 2, 3, 4], function(a, b) {
return a + b;
}, 0));
// → 1
结果只是1而不是预期的10.这里有什么大括号来改变输出?
答案 0 :(得分:6)
花括号正如您所问的那样:因为您在return
循环中包含了for
语句:
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++) {
current = combine(current, array[i]);
return current;
}
}
循环没有达到预期的效果,因为返回退出循环,实际上在返回值时起作用,因此只有数组的第一个元素:1
的值被折叠到var {{1}输出current
。鉴于:
1
返回预期输出:function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++) {
current = combine(current, array[i]);
}
return current;
}
,因为10
在返回值之前折叠所有数组元素。
答案 1 :(得分:5)
您需要在return
循环的块之外移动for
语句,因为return语句会立即结束函数和循环。
for (var i = 0; i < array.length; i++) {
current = combine(current, array[i]);
}
return current;
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++) {
current = combine(current, array[i]);
}
return current;
}
console.log(reduce([1, 2, 3, 4], function(a, b) {
return a + b;
}, 0));
&#13;
答案 2 :(得分:3)
此代码运行循环一次,并在第一个循环后立即返回:
for (var i = 0; i < array.length; i++) {
current = combine(current, array[i]);
return current;
}
这里我们在循环结束循环之后返回:
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;