0

I want to represent a board game in javascript and for that i need a bidimensional array.

I have different board sizes, so i need to initialize the array with the board size in the beginning. I am a java programmer so i know that in java when you want a bidimensional array you just do:

int board_size = 6;
String board = new String[board_size][board_size];

How can i achieve this with javascript? I have searched and found some ways of doing this, but all much less intuitive than this one.

2 Answers2

1

With JavaScript it is not a static language like Java. It is dynamic. That means you can create the array without a need to preset the size of the array, but if you want you can procreate an array of the size you want.

var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1

If you need to add to it just do

items.push([7,8]);

That will add the next element. Code taken from old stack overflow post: How can I create a two dimensional array in JavaScript?

Edited to properly make I in items same as variable declaration.

Community
  • 1
  • 1
Asheliahut
  • 901
  • 6
  • 11
1

It is not required like in Java or C#. The Javascript arrays grow dynamically, and they are optimized to work that way, so you don't have to set the size of your matrix dimensions upfront.

However, if you insist, you could do something like the following to pre-set the dimensions:

var board = [];
var board_size = 6;

for (var i = 0; i < board_size; i++) {
    board[i] = new Array(board_size);
}

So to summarize you just have three options:

  • Initialization with a literal (like in @Geohut answer)
  • Initialization with a loop (like in my example)
  • Do not initialize upfront, but on-demand, closer to the code that access the dimensions.
Faris Zacina
  • 14,056
  • 7
  • 62
  • 75
  • are there any drawbacks by doing this? – JoaoFilipeClementeMartins Feb 09 '15 at 10:05
  • 1
    Extra load time to preset the space when it's not needed. – Asheliahut Feb 09 '15 at 10:07
  • as @Geohut said you lose some time and space even if you will never access the matrix. However for a 6x6 matrix that is not even worth mentioning. Anyway, this is a technique commonly used by many people to preinitialize the dimensions. An alternative is just to initialize the dimensions in the code where you need to access the elements, so you initialize only what you need, when you need it. – Faris Zacina Feb 09 '15 at 10:09