Large 2D Array Always Returns Undefined

51 views Asked by At

I have a 2D array that absolutely will not return the values I need. I start off with this array:

var userdata:Array = new Array(new Array(1000),new Array(4))

Then I try to set all values to 0, with this:

this.onLoad()
{
    for (i = 0; i < 1000; i++)
        {
            for (j = 0; j < 4; j++)
            {
                userdata[i][j] = 0
                trace(userdata[i][j])
            }
        }
}

This trace returns 8 0s and then a giant amount of "undefined"s. I can't figure out why this would be. I try something like this as well:

userdata[5][0] = 0
trace(userdata[5][0])

It still returns "undefined". Can anyone help with this?

1

There are 1 answers

1
akmozo On BEST ANSWER

To understand why you got only 8 "zeros" and many undefined values, let's start by your array declaration :

var userdata:Array = new Array(new Array(1000),new Array(4));

Here you should understand that you have created an array with only 2 cells ( that's why userdata[5][0] is undefined ) : the 1st cell is an array of 1000 elements and the 2nd one is an array of 4 elements, and that's why you can only set 8 items ( 2 x 4 ) : the 4th first items from the 1000 of the the 1st cell + the the 4th first items from the 4 of the 2nd cell.

Let's return to your question, you want create a multidimensional array of 1000 rows and 4 columns. To start, we create an array of 1000 rows (cells) :

var a:Array = [1000];  // you can write it : new Array(1000);

Then, we create 4 columns for every row, and set values like this :

var i:Number, j:Number;
for (i = 0; i < 1000; i++)
{
    // create the 4 columns 
    a[i] = [4];     // you can write it : a[i] = new Array(4);

    for (j = 0; j < 4; j++)
    {
        a[i][j] = 0;
    }
}

Then we can verify our array :

trace(a[0][0]);     // gives : 0
trace(a[255][2]);   // gives : 0
trace(a[255][5]);   // gives : undefined, because we have only 4 columns
trace(a[1500][0]);  // gives : undefined, because we have only 1000 rows

Hope that can help.