dongyaofu0599 2014-10-27 19:41
浏览 566
已采纳

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

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

  • 写回答

2条回答 默认 最新

  • dpdt79577 2014-10-27 19:53
    关注

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

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

    1Douglas 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?