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

Kleo

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

Ori Drori

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);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to instantiate multi dimensional array in JavaScript?

Flutter 2 dimensional List/Array as Int/Object(class)

How to instantiate an object in a new class?

Convert 2 Dimensional Array into Object

How to properly instantiate a bi-dimensional array in Java

How to instantiate a Class<? extends Tag> object?

How to improve this with a 2 dimensional array

2 dimensional array of class objects in Javascript

Storing object into 2 dimensional array/list

2 dimensional array of managed object c++

Store object in 2 dimensional array in python?

How to group array 1 dimensional to array 2 dimensional?

How to flatten a 2-dimensional array into a 1-dimensional array

how to copy a 3 dimensional array to a 2 dimensional array?

instantiate object inside of class

How to convert multidimensional array into a 2 dimensional array?

How to instantiate an object of an Activity Class from non-Activity Class?

How to instantiate a Class object for a parameterized class using reflection and Guava TypeToken

How to anonymously instantiate an abstract class stored in a Class object in Java?

How to instantiate an object of a class from within the class itself?

instantiate and initialize multi dimensional array C#

instantiate class from class object

How to force numpy to interpret 2 dimensional array as 1 dimensional

How to create 2 dimensional json object in chsarp

How to post index of 2 dimensional object array element via url in javascript?

How to retrieve string from a 2 dimensional array

How to concatenate 2 strings in a multi dimensional array?

How to build a histogram of numpy 2 dimensional array

How to create two dimensional array with 2 arrays