javascript - 在递归中使用全局变量是一种好习惯吗

标签 javascript php algorithm recursion

我正在帮助某人完成他的学校作业 - 我们正在尝试编写递归函数(如果重要的话 - 使用 PHP 或 JavaScript)。

我很了解递归原理,但我还没有从“学术”的 Angular 写过任何递归原理。

使用全局变量存储结果是一种好习惯吗,比如:

var results = [];

var rec = function(a) {
    ...
    if (match)
        results.push(someValue);
}

或者我应该使用 return 将所有这些结果收集在一起(这会困难得多)?

最佳答案

最好使用尽可能少的全局变量,最好不使用1

为了避免在递归中需要全局变量,您可以使用使用闭包的内部函数:

var rec = function(a) {
    var someValue = [];
    function dorec() {
      // stuff happens
      if (match)
        results.push(someValue);
      }
    }
    dorec();  
}

1 Douglas Crockford

All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals. Implied global variables should never be used. Use of global variables should be minimized.

关于javascript - 在递归中使用全局变量是一种好习惯吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595562/

相关文章:

javascript - 是否可以在 CSS 转换期间保持对象适合?

javascript - 将多个变量传递到另一个页面

php - 我怎样才能从 git status "On branch master\n Nothing to commit.."到 "On branch master\n Your branch is up to date\n Nothing to .."?”

algorithm - 基于数学的排序插入

python - 计算机代数软件,用于最小化一组多项式中的运算次数

javascript - 多行标签 OpenLayers3

javascript - 如何在 Alpine.js 组件中获取数据属性的值?

javascript - 导出时是否可以在 SVG 中保存任意数据?

php如何在 session 超时时执行函数

java - 将二叉树转换为仅包含叶节点的链表