javascript - JS最大调用栈超过P5

标签 javascript class object recursion p5.js

我正在尝试编写程序来计算 p5.js 中最大的颜色连接 block 。问题是,当我递归调用它给出的框邻居时 - “最大调用堆栈超出”,我知道错误的含义,但我不知道为什么会发生。这是我的代码:

class Box {
  constructor(id, x, y, w, h, col, colId) {
    this.id = id;
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.col = col;
    this.colId = colId;
  }

  render() {
    fill(this.col);
    stroke(1);
    rect(this.x * this.w, this.y * this.w, this.w, this.h);
  }

  getNeighbour(visited, x, y) {
    if(x - 1 < 0 || x + 1 >= rows || y - 1 < 0 || y + 1 >= cols) {
      return -1; 
    }
    else {
      this.col = color(10,10,10);
      arr[x-1][y].getNeighbour(visited,x-1,y);
      arr[x+1][y].getNeighbour(visited,x+1,y);
      arr[x][y-1].getNeighbour(visited,x,y-1);
      arr[x][y+1].getNeighbour(visited,x,y+1);
    }
    if(!this.contains(this.id)) {
      visited.push(this.id); 
    }
    
    
    
  }
  
  contains() {
    for(let i = 0; i < visited.length; i++) {
      if(this.id == visited[i]) return true; 
    }
    return false;
  }
}

请告诉我问题出在哪里。我当时也试过做检查。首先是左边的邻居,效果很好。但是,当我也添加正确的时,会出现此错误。我想我已经满足了适当的默认情况,但实际情况可能有所不同。

最佳答案

代替:

else {
  this.col = color(10,10,10);
  arr[x-1][y].getNeighbour(visited,x-1,y);
  arr[x+1][y].getNeighbour(visited,x+1,y);
  arr[x][y-1].getNeighbour(visited,x,y-1);
  arr[x][y+1].getNeighbour(visited,x,y+1);
}
if(!this.contains(this.id)) {
  visited.push(this.id); 
}

尝试:

else if(!this.contains(this.id)) {
  visited.push(this.id);
  this.col = color(10,10,10);
  arr[x-1][y].getNeighbour(visited,x-1,y);
  arr[x+1][y].getNeighbour(visited,x+1,y);
  arr[x][y-1].getNeighbour(visited,x,y-1);
  arr[x][y+1].getNeighbour(visited,x,y+1);
}

进一步:我不确定 this.contains 是否正确,也许可以尝试:visited.contains... ?

关于javascript - JS最大调用栈超过P5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812726/

相关文章:

php - 根据短代码(路径)参数从对象中提取数据

javascript - jQuery 不在我的浏览器中运行

Javascript float 混淆

javascript - 处理 Redux 状态的函数的名称(例如 reducer 和选择器)

C# - 从基类获取页面的 BaseType.Name 和命名空间

python - 如何检查具有多个列表的 pandas 列中的项目是否重复?

javascript - 是否可以中断 "each"迭代,向其中一个值追加或添加某些内容,然后继续?

c++ - 私有(private)成员的作用是什么?

java - 在Java中从该类的主体内部实例化对象

java - 避免在 If 条件 SonarQube 错误中使用文字