javascriptarrays2ddimensional

Two Dimensional Array in Javascript Object


I want to create an Object that contains one or more two dimensional arrays in Javascript.

I tried it the following way (in this example I only try to add one two dimensional array):

var XSIZE = 8;  
var YSIZE = 8;  
var obj = {  
 field : new Array(XSIZE),  
 field[0] : new Array(YSIZE),  
 foo : 1,  
 bar : 100  
}

Info:
- This gives me a strange error "missing : after property id" which does not seem to make much sense
- Unfortunately I didn't find examples showing how to do this so far by using google
- If I don't add field[0] ... for creating the 2nd array it works.
- changing the XSIZE and YSIZE to numbers like new Array(8)... doesn't work.

I would really appreciate if somebody could show me how to do it or explain why I cannot do this at all and need to use some other method.

Thanks a lot!


Solution

  • The error "missing : after property id" is because JavaScript sees the field part of field[0] and expects a colon before the value of that field. Instead it gets an open bracket so it complains.

    You can't hard code an object definition that has its dimensions set up at run time. You have to build the object at run time as well. Like this perhaps

    var XSIZE = 8;  
    var YSIZE = 8;
    
    var obj = {  
     field : new Array(),  
     foo : 1,  
     bar : 100  
    }
    
    for (var i = 0; i < XSIZE; i++) {
      obj.field.push(new Array(YSIZE));
    }