javascript - 新手 : Why does this variable persist instead of getting reset?

标签 javascript functional-programming

我想这是一个新手问题,但我似乎无法弄清楚。我有一段来自 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,该函数接受两个操作数 - 这里称为elementtotal 到一个序列。 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/

相关文章:

functional-programming - 如何在ELM中将字符转换为ASCII值

EclipseFP 不工作

javascript - 警报框错误

Javascript:检查字符串中匹配的关键字数组

javascript - 在函数内部赋予值和在函数外赋予值有什么区别?

javascript - Nester在循环中延迟了Ajax调用

scala - 函数式编程是否可以减少冯·诺依曼瓶颈?

javascript - 将 'raw' javascript 数组缩减为更紧凑的(对象)数组

oop - 函数式编程是否被认为更多 "mathematical"?如果是这样,为什么?

javascript - <head> 元素在 DOM 中是否始终可用,即使在 HTML 标记中不存在?