我想这是一个新手问题,但我似乎无法弄清楚。我有一段来自 eloquent javascript 的关于reduce 函数的代码:
function forEach ( info, func ) {
for ( i = 0; i < info.length; i++) {
func(info[i]);
}
}
function reduce (combine, base, array) {
forEach(array, function(elem) {
base = combine(base, elem);
console.log("The base is: " + base);
});
return base;
}
function countZeroes(array) {
function counter(total, element) {
console.log("The total is: " + total);
return total + (element === 0 ? 1 : 0);
}
return reduce(counter, 0, array);
}
我不明白的是,每次调用函数时总共存储的零数量是如何的?为什么它会保留一个正在运行的选项卡,而不是每次都被清除?
最佳答案
reduce的结构是它应用一个函数f
,该函数接受两个操作数 - 这里称为element
和total
到一个序列。 element
是序列(数组)中下一个未处理的项目; total
是上次调用 f
的结果。
概念上,reduce(f, 0, [1,2,3])
扩展为 f(3,f(2,f(1,0))
。
现在,回答你的问题:运行的total
存储在counter
的调用之间,存储在reduce<内的变量
.base
中
关于javascript - 新手 : Why does this variable persist instead of getting reset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18472399/