如何创建2D数组阵列?

时间:2018-06-03 15:03:04

标签: javascript arrays multidimensional-array p5.js conways-game-of-life

我正在完成这项任务,我需要构建一个版本的生命游戏。我无法正确设置这个2D阵列,以便我可以跟踪细胞是“活着”还是“死亡”。我好像已经撞墙了,我需要有人让我朝着正确的方向前进。

var grid;

function setup () {
 createCanvas(400, 400);
 grid = new Grid(20);
}

function draw () {
 background(245);

   grid.draw();
}

class Grid {
  constructor (cellSize) {
   this.cellSize = cellSize;
   this.numberOfColumns = height/this.cellSize;
   this.numberOfRows = width/this.cellSize;

   this.cells = new Array(this.numberOfColumns);
   this.rows = new Array(this.numberOfRows);
   this.twoDArray = new Array(this.cells);

  for (var i = 0; i < this.cells; i++) {
   this.twoDArray[i] = new Array(this.rows);
  }


 // for (var column = 0; column < this.numberOfColumns; column ++) {
  // for (var row = 0; row < this.numberOfRows; row++) {
   // this.cells[column][row] = new Cell(column, row, cellSize);
  //}
  // }

 print(this.cells);
}

draw() {
 for (var column = 0; column < this.numberOfColumns; column ++) {
   for (var row = 0; row < this.numberOfRows; row++) {
     fill(240); 
     noStroke();
     rect(column * this.cellSize + 1, row * this.cellSize + 1, this.cellSize - 1, this.cellSize - 1);
    }
  }
 }
}
   class Cell {
    contructor (column, row, cellSize) {
     this.column = column;
     this.row = row;
     this.cellSize = cellSize;
     isAlive = false;
    }
  }

每当我尝试取消注释上面评论的代码时,控制台会说:TypeError:无法设置'0'的属性未定义。我确定我错过了一些明显的东西,但我似乎无法看到它是什么。您将给予的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您无法将this.cells用作多维数组,因为它按照new Array填充了空元素。

您应该将代码更改为:

for (var column = 0; column < this.numberOfColumns; column ++) {
  this.cells[column] = []; // or use here new Array or similar
  for (var row = 0; row < this.numberOfRows; row++) {
    this.cells[column][row] = new Cell(column, row, cellSize);
  }
}