how to create multidimensional arrays in javascript

we can create arrays in javascript with a notation like

var a : float[];

but i can not create multidimensional arrays in javascript like

var a : float[,];

how can i create a two dimensional array in javascript? i want .NET arrays and don't want array class arrays.

While you can use multi-dimensional arrays in Javascript, the syntax for creating them is missing. Fortunately you can get around that by using type inference, as shown in this helper script.

This question has been moot since Unity 3.2. In fact you can do

var a : float[,];

with no problem.

thank you guys for the answers. so unity's javascript compiler or mjs (mono jscript compiler) is not capable of declaring multiDimensional arrays but can use them. they are first class members of the .NET framework and are not language dependent so you can declare them in C# and return them and use them in JS. in fact when you declare an array in C# it will crate an instance of System.Array or one of it's children. the problem is js don't support this syntax for rectangular arrays but surely it can use the class. you should declare a static method for that for easier use.

static int[,] intArray(int d1,int d2)
{
   return new int[d1,d2];
}

you can define a function for each type of use reflection to create a generic method. generics themselves are not supported in js so you can not simply write

static t[,] arr<t>(int d1,int d2)
{
   return new t[d1,d2];
}

i mean you can write but in js you can not write

var t = arr<int>(10,30);

you can make a generic method using typeof operator and system.type class and ... remember if your array is an array of a reference type (a class) then you should populate all elements before returning it.

public static string[,] createString (int x,int y)
{
string s[,] = new string[x,y]; //this will declare an array of string in size x X y but all elements are null.
//you should populate them yourself by hand.
for (int i=0;i<x;i++)
for (int j=0;j<y;j++)
s[i,j]= "new string"; // for other types of classes you might use new classname();
//then you can return s
return s;
}

You can just use this:

var YourArrayHere = new Array();
YourArrayHere.length = [first dimension array length here];
for(var count = 0; count < YourArrayHere.length; count++)
{
    var TempSecondArray = new Array();
    TempSecondArray.length = [sec dimension array length here];
    YourArrayHere[count] = TempSecondArray;
}

And it can be accesed with

YourArrayHere[First dimension index][Second dimension index]

It may be long… but this is the way i do it :slight_smile: