1

I'm trying to figure out how to create a multidimensional array with fixed dimensions.

This stack overflow thread said a three dimensional array could be made like this:

var arrayName = new Array(new Array(new Array()));

and this tutorial said a single-dimensional array of fixed length could be created like this:

var varname = new Array(3);

I'm not sure how to make an multidimensional array of fixed size (I'm making one to create a hexagon grid). My guess is that you would have to do it something like this:

var hexgrid_radius = 20;

var array1 = new Array(hexgrid_radius);

for(int i = 0; i < array1.length; i++) {

     var array2 = new Array(hexgrid_radius);
     array1[i] = array2;

     for(int j = 0; j < array2.length; j++) {

         var array3 = new Array(hexgrid_radius);
         array2[j] = array3;
     }
}

1 Answer 1

2

Don't use the Array constructor, just use array literals. And you can't use type declarations like int i in JavaScript. Something like this is what you want (taken from my own hex-tile based game):

var size = 20;
var grid = [];
for ( var row = 0; row < size; row++ ) {
  grid[ row ] = [];
  for ( var col = 0; col < size; col++ ) {
    grid[ row ][ col ] = new HexTile( row, col );
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Aren't those still dynamic arrays though? Their size is only be increased as necessary to accomodate inserting into a larger index. I guess there is no reason I couldn't use dynamic arrays, but I thought it was considered a good practice to use arrays of fixed size when you can and you know the array size won't be changing.
JavaScript only has dynamic arrays. Try this: var array = new Array( 10 ); array.pop(); console.log( array.length ); // 9
If you want some kind of data structure that truly acts like a fixed-size array, you need to wrap an array with an object that handles the array for you. Don't do that; you really don't need it for this case. It sounds like you're coming from a language with static typing, fixed length arrays, etc. JavaScript doesn't have those concepts - variables are dynamically typed and arrays are dynamically sized.
On top of that, garbage is automatically collected, functions are objects, objects have prototypes instead of classes, and instead of pausing until input we have the asynchronous callback loop. Learn JavaScript, don't just try to apply the techniques of your mother tongue to JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.