18910140161

JavaScript-未捕获的TypeError:this.ActiveArray[I]未定义-堆栈溢出

顺晟科技

2022-10-18 12:51:27

146

我一直有个问题。我正在尝试用JavaScript制作康威的生活游戏,使用一个大的游戏类。然而,当我运行我的成品时,尽管在另一个函数中以完全相同的方式使用该函数,我还是得到了这个错误。我在这里声明了数组:

<代码>类游戏{构造函数(){this.cellsize=5;this.alivecolor=";#ff756b";this.deadcolor=";#181818";this.rows=math.floor(canvas.height/this.cellSize);this.columns=math.floor(canvas.width=this.cellsize);//两个生命周期(活动与过去得小版本)得变量this.inactiveArray=[];this.ActiveArray=[];

并在以下两个方法中调用数组:

class Game {
 constructor() {
  this.cellSize = 5;
  this.aliveColor = "#FF756B";
  this.deadColor = "#181818";
  this.rows = Math.floor(canvas.height / this.cellSize);
  this.columns = Math.floor(canvas.width = this.cellSize);
  //Variables for two lifecycles, active and past iteration
  this.inactiveArray = [];
  this.activeArray = [];

(对不起,缩进不好,这是我的第一篇文章)ArraySinit函数运行时肯定没有错误,因为我已经尝试调试了所有的内容(没有成功)。在drawCells()中的行";if(this.ActiveArray[I][J]===1){";上抛出错误我不知道为什么,因为我已经清楚地定义了数组并使用了它。


顺晟科技:

我注意到

的一件事,cidom10,是您的行 this.drawCells = () => { for (let i=0; i<this.rows; i++) { for (let j=0; j<this.columns; j++) { let color; if (this.activeArray[i][j] === 1) { color = this.aliveColor; } else { color = this.deadColor; } ctx.fillStyle = color; ctx.fillRect(i * this.cellSize, j * this.cellSize, this.cellSize, this.cellSize); } } } this.arraysInit = () => { for(let i=0; i<this.rows; i++) { this.activeArray[i] = []; for(let j=0; j<this.columns; j++) { this.activeArray[i][j] = 0; } } this.inactiveArray = this.activeArray; } 有一个=符号,看起来应该是除号 this.columns = Math.floor(canvas.width = this.cellSize);。不知道这只是一个打字错误还是什么。

但是,我认为真正的问题在于行/,它将this.inactiveArray = this.activeArray;设置为对Object.assign,可以使用this.inactiveArray = Object.assign([], this.activeArray);

activeArray

我敢打赌,您在某个时候修改了this.inactiveArray = this.activeArray;,这也修改了this.inactiveArray = Object.assign([], this.activeArray); ,并导致了一些索引问题,这就是这些错误的根源。

不过,

如果没有更多的代码,这一切都是理论上的。

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航