简体   繁体   中英

Is it possible to initialize a bidimensional array in javascript like in java?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM