Javascript递归变量范围

时间:2014-06-02 09:18:58

标签: javascript variables recursion scope

我有一个递归函数(参见代码),如果我从深度5开始

分支时

execute(depth-1,x,y,width/2,height/2);

完成,

的深度不是5
execute(depth-1,midX,y,width/2,height/2);

但是1,它会产生混乱。您可以在此处查看算法:http://jsfiddle.net/g4p66/

它应该产生看起来像迷宫的东西(一个设计糟糕的迷宫,哈哈)

    function execute(depth,x,y,width,height){
        if(depth > 0){
            var midX = (x+width)/2;
            var midY = (y+height)/2;
            c.save();
            c.beginPath();
            c.moveTo(midX,midY);
            var from = Math.floor(Math.random()*4);
            if(from === 0){
                c.lineTo(midX,y);
            } else if(from === 1){
                c.lineTo(x+width,midY);
            } else if(from === 2){
                c.lineTo(midX,y+height);
            } else if(from === 3){
                c.lineTo(x,midY);
            }
            c.stroke();
            c.restore();
            execute(depth-1,x,y,width/2,height/2);
            console.log(depth);
            execute(depth-1,midX,y,width/2,height/2);
            execute(depth-1,x,midY,width/2,height/2);
            execute(depth-1,midX,midY,width/2,height/2);
        }
    }

编辑: 我错误地读了console.log,所以让我很困惑。 主要原因是我的midX midY计算错误,应该是:

var midX = (x+(x+width))/2;
var midY = (y+(y+height))/2;

1 个答案:

答案 0 :(得分:2)

您没有可变范围问题,但解释日志时存在逻辑问题。

您看到的第一个console.log不是递归顶层的那个,而是最深层的那个,因为这是执行顺序。

以下是发生的事情:

execute(5)
   execute(4)
      execute(3)
         execute(2)
            execute(1)
                execute(0) : depth <=0 -> return
            console.log(depth) -> logs 1

当你到达日志时,你可以检查你自己的screehot你在递归的深处:

enter image description here