gpt4 book ai didi

javascript - 递归javascript函数不会返回父调用数据?

转载 作者:行者123 更新时间:2023-12-03 11:20:37 24 4
gpt4 key购买 nike

我正在开发一个 HTML5/JS 项目,在 Canvas 上绘制二叉分形树。

HTML5::

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas1" width="500" height="500"></canvas>
<br />
<script src="tree.js"></script>
<button id="button1" type="button" onclick="main()">Start</button>
</body>
</html>

Javascript::

var scale = 0.5;
var min_len = 1;
//setup canvas
var c = document.getElementById("canvas1");
var ctx = c.getContext("2d");
ctx.moveTo(250, 500);

//returns length of branch
function len(branch) {

return Math.sqrt( Math.pow(branch.len_x, 2) + Math.pow(branch.len_y, 2) );
}

//draws from start to length of branch
function drawBranch(start, branch) {

ctx.moveTo(start.x, start.y);
ctx.lineTo(start.x + branch.len_x, start.y - branch.len_y);
ctx.stroke();
}

//recursively builds binary fractal tree
function makeChildren(start, theta, parent) {

if(len(parent) >= min_len) {
drawBranch(start, parent);

//linear transformation applied to parent branch which rotates and scales to produce child branch
child = {len_x: ( parent.len_x * Math.cos(theta) - parent.len_y * Math.sin(theta) ) * scale,
len_y: ( parent.len_x * Math.sin(theta) + parent.len_y * Math.cos(theta) ) * scale};

//recursively build left and right branches of tree
makeChildren( {x: start.x + parent.len_x, y: start.y - parent.len_y}, theta, child);
makeChildren( {x: start.x + parent.len_x, y: start.y - parent.len_y}, theta * (-1), child);
}
}

function main() {

//initialize tree
makeChildren( {x: 250, y: 500}, Math.PI / 4, {len_x: 0, len_y: 100} );
}

当我运行代码时,它会产生一种向左的螺旋结构(抱歉,还不能发布图像)。

问题在于 makeChildren 函数中的长度检查,一旦 if 语句不再为 true,即当分支太小时,程序就会陷入递归循环,其中大小仍然太小。这是分支长度的控制台日志::

[日志] 100(tree.js,第 24 行)

[日志] 49.99999999999999(tree.js,第 24 行)

[日志] 25(tree.js,第 24 行)

[日志] 12.5(tree.js,第 24 行)

[日志] 6.25(tree.js,第 24 行)

[日志] 3.125(tree.js,第 24 行)

[日志] 1.5624999999999998(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

[日志] 0.7812499999999999(tree.js,第 24 行)

它应该到达递归循环的基本情况(分支长度太小)并返回到前一个递归循环,但看起来它只是一遍又一遍地不断检查相同的长度,0.78125。我不明白为什么,请帮忙!

最佳答案

checking the same length, 0.78125, over and over again

每级递归都会使调用次数加倍。它将达到基本情况...128(?)次。

it produces a left-ward facing spiral kind of structure

事实上,有一个全局 child 变量。当第一个子 makeChild 运行时,它会重新分配此全局 child 变量,第二个子makeChild 以此修改后的变量开始。

你可能想要

var child = {len_x: ...

http://jsfiddle.net/hLxe4fx1/

关于javascript - 递归javascript函数不会返回父调用数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com