How to declare and initialize multidimensional arrays JS?

I'm trying to instantiate a grid using cubes with this shape

alt text

I'm trying to use a multidimensional array for this but I have problems initializing the array with set values.

public var multiDimensionalArray: int[,] =  [

Above is the first method I've tried but it throws the following error

Assets/TetrisPiece.js(7,45): BCE0022: Cannot convert 'int[][]' to 'int[,]'.

I've also tried storing an array in a array

var myArray: int[4];
myArray[0] = new int[0,1,1,0];
myArray[1] = new int[1,0,0,1];
myArray[2] = new int[1,0,0,1];
myArray[3] = new int[0,1,1,0];

But this shows the following error:

Assets/TetrisPiece.js(1,17): UCE0001: ';' expected. Insert a semicolon at the end.

I suspect a syntax error but I haven't been able to find what. Thanks in advance.

Declaring an array the way you did initially results in a jagged array. If you leave off the type, type inference will type it as a jagged array automatically:

public var multiDimensionalArray = [

(The type for this is int[][], not Array.) Then you can do


instead of


Jagged arrays aren't quite the same thing as multidimensional arrays, but it would work well enough. If there's an easy syntax to initialize multidimensional arrays in JS by filling them with initial values, I don't know what it is. If you really need a "proper" multidimensional array, you might have to do it the hard way:

public var multiDimensionalArray : int[,];
multiDimensionalArray[0,0] = 0;
multiDimensionalArray[0,1] = 1;

public var multiDimensionalArray: int[,] = new int[4,4];

multiDimensionalArray[0,0] = 1;
multiDimensionalArray[0,1] = 1;
multiDimensionalArray[0,2] = 0;
multiDimensionalArray[0,3] = 1;
multiDimensionalArray[1,0] = 0;
multiDimensionalArray[3,3] = 0;

You can also turn this into a for loop to set the values.

I am trying this for making grid with each index containing card object but its not working. Same error.

function Start () {

var i:int = 0;
var j:int = 0;
aCards = new Array(); //Just Ignore it
aGrid = new Array();
aCardsFlipped = new ArrayList(); //Just Ignore it
for(i=0; i<4; i++)
	aGrid *= new Array();*
  •   for(j=0; j<4; j++)*
  •   {*

_ aGrid*[j] = new Card(); //Assigning object of class card to grid*_
* }*
* }*

JavaScript doesn't actually have support for multi-dimensional arrays, but you can nest arrays. For most programming purposes, nested arrays are equivalent to multi-dimensional arrays. Therefore we are not going to worry about the differences between them here.

To create a nested array, you just define an array element as being an array.

var outerA = new Array();
outerA[0] = new Array();
outerA[1] = new Array();
outerA[2] = new Array();

When using array literals, the same effect can be achieved by nesting square brackets.

var aName = [[1,2,3],['a','b','c']];

// is the same as

var aName = new Array();
aName[0] = [1,2,3];
aName[1] = ['a','b','c'];