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;
     }
}
Community
  • 1
  • 1
user244145
  • 73
  • 1
  • 11

1 Answers1

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 );
  }
}
sbking
  • 7,630
  • 24
  • 33
  • 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. – user244145 Dec 15 '13 at 11:08
  • 1
    JavaScript only has dynamic arrays. Try this: `var array = new Array( 10 ); array.pop(); console.log( array.length ); // 9` – sbking Dec 15 '13 at 11:15
  • 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. – sbking Dec 15 '13 at 11:16
  • 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. – sbking Dec 15 '13 at 11:29