首页 > 解决方案 > 如何避免“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);
    }




}

}

标签: javascriptrecursion

解决方案


发生这种情况是因为您从未初始化- 它ivar发送到全局范围并被每个函数调用覆盖。


推荐阅读