JavaScript通过引用问题传递数字,简单的递归函数
问题描述:
我已经构建了这个简单的递归函数。JavaScript通过引用问题传递数字,简单的递归函数
递归很容易看到,因为它应该绘制一个像嵌套模式的框。这些盒子每次迭代都会略微向下移动,以便在有重叠线条的地方更清晰。
___________
1. | |
| |
| |
| |
| |
|___________|
___________
2. |___________|
| | |
| | |
| | |
| | |
|_____|_____|
|_____|_____|
__ __ __ __
3. |___________|
|_____|_____|
| | | | |
| | | | |
| | | | |
|__|__|__|__|
|__|__|__|__|
|__|__|__|__|
http://codepen.io/alan2here/pen/reFwo
var canvas = document.getElementById('canvas').getContext('2d');
box(50, 50, 150, 150);
function box(x, y, width, height) {
// draw the box
line(x, y, x + width, y);
line(x, y, x, y + height);
line(x, y + height, x + width, y + height);
line(x + width, y, x + width, y + height);
// continue with a tree like nested pattern of sub-boxes inside this one.
if (width > 100) {
width2 = width * 0.5;
box(x, y + 5, width2, height);
box(x + width2, y + 5, width2, height);
}
}
function line(x, y, x2, y2) {
canvas.beginPath();
canvas.moveTo(x, y);
canvas.lineTo(x2, y2);
canvas.closePath();
canvas.stroke();
}
然而,这种突然停止工作在迭代3,如可如果width > 100
可以看出改变为width > 50
。
__ __ __ __
3. |_____ |
|__|__| |
| | | |
| | | |
| | | |
|__|__|_____|
|__|__|
|__|__|
看来,如果值可以得到通过参考,他们不应该是过去了,但是我想通过复制值传递的JS数字,更重要的是我创建的大部分传递的值从从头开始,例如..., x + width, ...
和width2 = width * 0.5
。
为什么程序无法正常工作。
感谢Benni的轻微更正。
答
变量总是在Javascript中值传递。它甚至不支持通过引用传递参数。
的问题是,您使用的是全局变量:
width2 = width * 0.5;
当您第一次循环调用它会改变全局变量的值,所以第二个递归调用将使用来自值最后一次迭代。
声明变量的函数,以便它是本地的:
var width2 = width * 0.5;
你说得很对,先生 – 2014-10-03 11:08:59
哇,默认情况下不在你的范围内声明?非常感谢你。像这样的静态是一个潜在的强大的功能,但我相信,如果需要像'var'这样的术语来表示全局定义,而不是局部的话,会更好。 – alan2here 2014-10-03 11:11:31
@ alan2here欢迎使用Javascript! :d – 2014-10-03 11:12:08