javascript - 如何避免“RangeError:超出最大调用堆栈大小”错误?
问题描述
我目前正在研究一种称为递归除法的迷宫生成算法。该算法很容易理解: 第 1 步:如果您的房间的高度小于宽度,用一条垂直线划分您的网格/房间。如果高度大于宽度,则用一条水平线分隔您的房间。第 2 步:对由线条创建的子室重复第 1 步。你想重复这些步骤直到你得到一个迷宫(直到宽度或高度等于 1 个单位)。
这个算法的问题是 JavaScript 打印出 RangeError,这意味着我调用了太多次创建迷宫的函数(我试图用递归函数来实现这个算法)。有没有办法避免/防止这种情况发生?或者我是否在我的代码中遗漏了一些使算法无法正常工作的重要内容?
我试图实现一个蹦床功能,但由于我是一个初学者,我只是不太了解它来实现我自己。我也重新启动了我的整个项目 3 次,希望我能想出一种不同的方法来解决这个问题,但每次我都会遇到同样的错误。
我的代码在这里:
//leftCord = the left most x coordinate of my chamber/grid, upCord = the upmost y coordinate of my
grid etc.
//(0, 0) IS POSITIONED IN THE LEFT TOP NODE OF MY GRID
function createMaze(leftCord, rightCord, upCord, downCord) {
var height = Math.abs(downCord - upCord);
var width = Math.abs(rightCord - leftCord);
if (height < 2 || width < 2) {
//The maze is completed!
return;
} else {
if (height < width) {
//cut the chamber/grid vertically
//Getting a random number that's EVEN and drawing the function x = 'random number' on the grid
var x = randomNum(leftCord / 2, rightCord / 2) * 2;
var lineX = [];
for (i = upCord; i < downCord; i++) {
lineX.push(grid[i][x]);
}
//Making a random door/passage and making sure it's ODD
var randomDoor = randomNum(0, lineX.length / 2) * 2 + 1;
lineX.splice(randomDoor, 1);
//Drawing the line
for (i = 0; i < lineX.length; i++) {
lineX[i].className = "wall";
}
//Making the same thing again, but with the left and right sub-chambers that were created by the line
createMaze(leftCord, x, upCord, downCord);
createMaze(x, rightCord, upCord, downCord);
} else {
//cut the chamber/grid horizontally
//Getting a random number that's EVEN and drawing the function y = 'random number' on the grid
var y = randomNum(0, downCord / 2) * 2;
var lineY = [];
for (i = leftCord; i < rightCord; i++) {
lineY.push(grid[y][i]);
}
//Making a random door/passage and making sure it's ODD
var randomDoor = randomNum(0, lineY.length / 2) * 2 + 1;
lineY.splice(randomDoor, 1);
//Drawing the line
for(i = 0; i < lineY.length; i++){
lineY[i].className = "wall";
}
//Making the same thing again, but with the upper and lower-chambers that were created by the line
createMaze(leftCord, rightCord, upCord, y);
createMaze(leftCord, rightCord, y, downCord);
}
}
}
解决方案
发生这种情况是因为您从未初始化- 它i
被var
发送到全局范围并被每个函数调用覆盖。
推荐阅读
- groovy - 在 groovy 中获取 java.lang.NullPointerException 而 JSONPATH 查找
- raku - 在 raku REPL 中定义后缀运算符的问题
- r - 根据数据表的列名具有不同线条颜色和轨迹样式的线图
- c# - 有没有办法在 C# 中填充已经打开的网页?
- android - 运行“flutter doctor --android-licenses”时如何修复?
- r - 在 R 中使用表格进行操作
- python - 如何等到工具栏出现在 skribbl.io | Python
- couchdb - Cloudant 对可空字段进行排序
- javascript - MERN 应用程序 - 渲染中的反应状态 - 类型错误:无法读取未定义的属性“用户名”
- python - 如何检查午夜是否刚刚过去?