PDA

View Full Version : Syntax for 2D Arrays


don simon
07-17-2006, 04:54 PM
Hi,
I wanna make a 2D array to hold six x and y values, i.e. 6x2 values from posArray[0][0] to posArray[5][1]. How can I define it without adding values?

I tried using
var posArray:Array = new Array([],[]);
but it only creates a 2x2 array. It works fine reading/writing to all positions using this:
var posArray:Array = new Array([00, 01],[10, 11],[20, 21],[30, 31],[40, 41],[50, 51]);
but it's quite ugly programming adding all those numbers that aren't to be used.

This should be quite basic, but I can't seem to find the correct syntax... :confused:

senocular
07-17-2006, 04:59 PM
Thats "correct" in thats how you create 2D arrays. How you apply it in code is up to you. You can use new Array + [] or even new Array + new Array, or probably the most prefered, [] + [];
var posArray:Array = [
[00, 01],
[10, 11],
[20, 21],
[30, 31],
[40, 41],
[50, 51]
];

don simon
07-17-2006, 08:51 PM
That's what I thought, but then this is weird: After defining my array and then traversing and filling it with a for statement, it works after having filled in temporary values (like in your example), but not after var posArray = new Array([],[]); , only the first four (2x2) values work then.

How do you mean that I should do to define it without filling in the values?


for(var i=0; i<6; i++) {
imgPosArray[i][0] = i * 100; // x position
imgPosArray[i][1] = 40; // y position
}

senocular
07-17-2006, 08:58 PM
you have to make your arrays before filling them. If you dont, it wont work.

don simon
07-17-2006, 09:08 PM
of course, but in the 1D case, you can write
size = 6;
var a:Array = new Array(size);
and then fill it. I want to make the same for a 2D array. I read my xml-file, define the array depending on the xml file's size and then fill it with the values. Now I'm into doing it with push(), but I would like a slicker solution...