简体   繁体   中英

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).

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)?

It is good practice to use as little global variables as possible, preferrably none .

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();  
}

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

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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