Search code examples
javascriptarraysclassinstantiation

How to instantiate a class object with a 2 dimensional array?


I'm trying to insantiate an object with a 2 dimensional array but the following code doesn't seem to work:

class Board {
  constructor(row,col){
    this.board=[];
    for (var i=0; i<row; i++){
      for (var y=0; y<col; y++){
        this.board[i][y]=0;
      }
    }
  }
}

var board = new Board(10,10);

https://jsbin.com/worepeb/edit?js,console


Solution

  • You need to init the sub-array before you can fill it with numbers - this.board[i] = [];:

    class Board {
      constructor(row,col){
        this.board=[];
        for (var i=0; i<row; i++){
          this.board[i] = []; // init this.board[i]
          for (var y=0; y<col; y++){
            this.board[i][y]=0;
          }
        }
      }
    }
    
    var board = new Board(10,10);
    
    console.log(board);

    You can also use Array.from() to init the board:

    class Board {
      constructor(row,col){
        this.board = Array.from({ length: row }, () => 
          Array.from({ length: col }, () => 0)
        );
      }
    }
    
    const board = new Board(10,10);
    
    console.log(board);