简体   繁体   English

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

[英]Is it good practice to use global variables in recursion

I'm helping someone on his school assignment - we're trying to write recursive function (if it matters - either in PHP or JavaScript). 我正在帮助某人完成他的学校作业-我们正在尝试编写递归函数(如果重要的话-使用PHP或JavaScript)。

I understand principles of recursion quite well, but I haven't wrote any of those from "academic" viewpoint. 我非常了解递归的原理,但是我还没有从“学术”角度写过任何递归原理。

Is it good practice to use global variable to store result, something like: 使用全局变量存储结果是否是一种好习惯,例如:

var results = [];

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

Or should I use return for collecting all those results back together (which would be much more difficult)? 还是应该使用return来将所有这些结果重新收集在一起(这会更加困难)?

It is good practice to use as little global variables as possible, preferrably none 1 . 优良作法是使用尽可能少的全局变量,最好不使用1

To avoid the need for a global variable in recursion, you can use an inner function that uses a closure: 为了避免在递归中使用全局变量,可以使用使用闭包的内部函数:

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

1 Douglas Crockford states 1 道格拉斯·克罗克福德州

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. JavaScript不需要这样做,但是这样做使程序更易于阅读,并且更易于检测可能成为隐式全局变量的未声明变量。 Implied global variables should never be used. 隐含的全局变量绝对不能使用。 Use of global variables should be minimized. 全局变量的使用应最小化。

To expand on the existing comments and to give you a concrete example, here is the code for recursively adding the even numbers to the given array: 为了扩展现有注释并为您提供一个具体示例,下面是将偶数递归添加到给定数组的代码:

var match;
var rec = function(a, res) {
    if (a < 0) {
        return res;
    }

    match = a % 2 == 0;

    if (match) {
        res.push(a);
    }
    return rec(a - 1, res);
}

var results = rec(10, []);

alert(results);

and the fiddle: http://jsfiddle.net/xukukggL/ 和小提琴: http : //jsfiddle.net/xukukggL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM