如果我从深度 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;
最佳答案
您没有遇到变量范围问题,而是解释日志时出现逻辑问题。
您看到的第一个 console.log
不是递归顶层的日志,而是最深层的日志,因为这是执行顺序。
发生的情况是这样的:
execute(5)
execute(4)
execute(3)
execute(2)
execute(1)
execute(0) : depth <=0 -> return
console.log(depth) -> logs 1
当您到达日志时,您可以检查自己的屏幕截图,看看您是否已深入递归:
关于Javascript递归变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23991123/