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;

关于Javascript 通过简单的递归函数通过引用传递数字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26177727/

相关文章:

javascript - 我如何在渲染方法 React-Native 上调用数组对象中的 rowData 值

Javascript/jQuery 检查对象中的重复值

javascript - 访问 Angular $http

javascript - mootools javascript 模板引擎

javascript - Express 4 Multer/req.body 和 res.json 未定义

javascript - 是否可以在友好的 iframe 中注册 Service Worker?

带有预编译脚本的 Javascript 模板引擎?

javascript - 如何在 React Native 中显示从两个不同键值过滤的 JSON 数据

javascript - 如何在 JavaScript 中使用单个函数进行多个输入

javascript - 离开页面时继续计数的计时器