Bobby Francis Joseph
Bobby Francis Joseph

Reputation: 600

Problem with 2d Array in AS3

I am encountering a strange problem. I am trying to generate a matrix with value of elements either 1 or 0 (filled randomly). I am storing the values into a 2D array. This is code on the first frame. Everything seems to be working fine.

var multiArr:Array = new Array([2], [2]);


    function generateMatrixXML() {

    for(var i:uint = 0; i < 2; i++)
    {
        for(var j:uint = 0; j < 2; j++)
        {
            multiArr[i][j] = getRandomNumber(0,1);;

        }
    }
    trace(multiArr);
    }

    function getRandomNumber(lower,upper):Number {
        return Math.floor(Math.random()*(1+upper-lower))+lower;
    }


    generateMatrixXML();

When I change the value of row and column to 3 I get an error.

var multiArr:Array = new Array([3], [3]);


function generateMatrixXML() {

for(var i:uint = 0; i < 3; i++)
{
    for(var j:uint = 0; j < 3; j++)
    {
        multiArr[i][j] = getRandomNumber(0,1);;

    }
}
trace(multiArr);
}

function getRandomNumber(lower,upper):Number {
    return Math.floor(Math.random()*(1+upper-lower))+lower;
}


generateMatrixXML();

TypeError: Error #1010: A term is undefined and has no properties. at matrixArray_fla::MainTimeline/generateMatrixXML() at matrixArray_fla::MainTimeline/frame1()

Got any idea as to what is the reason for error

Upvotes: 0

Views: 4258

Answers (3)

Siva
Siva

Reputation: 359

Creating a 2D Array

var multiDimensionalArray:Array = new Array();
var boolArray:Array;
var MAX_ROWS = 5;
var MAX_COLS = 5;

//initalize the arrays
for (var row = 0; row <= MAX_ROWS; row++)
{
    boolArray = new Array();

    for (var col = 0; col <= MAX_COLS; col++)
        boolArray.push(false);
    }

    multiDimensionalArray.push(boolArray);
}

//now we can set the values of the array as usual
for (var row = 0; row <= MAX_ROWS; row++)
{
    for (var col = 0; col <= MAX_COLS; col++)
        boolArray[row][col] = true;
        trace('boolArray ' + row + ',' + col + ' = ' + boolArray[row][col]);
    }
}

Upvotes: 1

J. Holmes
J. Holmes

Reputation: 18546

I know this question has already has an accepted answer, but I think it worth noting there are are few different solutions. While, yes, AS3 does not naively support 2D arrays, it does support arrays of arrays, which can be used to replicate its functionality.

To brute force initialize an array of arrays, which is what the op is trying to do, there is a somewhat straight-forward approach. To make a 3x3 array, could write:

var arr5:Array = new Array(new Array(3), new Array(3), new Array(3));

or perhaps even more simply, and cryptic:

var arr6:Array = [[0,0,0],[0,0,0],[0,0,0]] // Create a 3x3 array with all values set to 0

and if you were going to initialize the values right away in a loop, you could even get away with:

var arr6:Array = [[],[],[]] // Create an empty '2D' array with 0 cols and 3 rows

Now, I wouldn't make a 10x10 array like this, but its simple and it works for smaller multi-dimensional arrays. For larger multi-dimesnional arrays it would probably be best to initialize in a loop, like the accepted answer.

But this also might be a good time to talk about Vectors. If you are making an array and you know that its always going to hold a specific class (and especially if its always going to be of a specific length), then you can leverage the vector class.

var rows:uint = 10, cols = 10;
var multiArray:Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>(rows, true);
for(var i:uint = 0; i < rows; i++) multiArray[i] = new Vector.<Number>(cols, true);

This will create a 10x10 2D array of Numbers that is fixed in size. There are definitely some benefits to using a strongly-typed Vector over an Array.

The reason the second example fails is because, like the comment in the accepted answer, both times a 1x2 array is created. The expanded form is

// var multiArray:Array = new Array([3],[3])
var multiArr:Array = []
multiArray[0] = [3]
multiArray[1] = [3]

Notice that multiArray[0][1] is undefined. But even more importantly, multiArray[2] is undefined all together. It fails when trying to reference multiArray[2][0] cause its just not there.

Also note that the Array in flash are spare arrays (which the Vector class is dense). This means you can do things like:

var arr7:Array = [];
arr7[100] = 1;

It leaves the positions 0 through 99 as undefined and just sets index 100 to 1

Upvotes: 3

shanethehat
shanethehat

Reputation: 15580

This line:

var multiArr:Array = new Array([3], [3]);

Is creating an array containing two arrays, each of which has one element containing the number 3. That means that when you get to the third iteration multiArr[i] is undefined. This is clearly a misunderstanding of how to define arrays in AS31

You actually need to create your arrays within the loop:

var multiArr:Array = [];
var iterations:int = 3;

function generateMatrixXML() {
    for(var i:uint = 0; i < iterations; i++)
    {
        multiArr[i] = [];
        for(var j:uint = 0; j < iterations; j++)
        {
            multiArr[i][j] = getRandomNumber(0,1);

        }
    }
    trace(multiArr);
}

function getRandomNumber(lower,upper):Number {
    return Math.floor(Math.random()*(1+upper-lower))+lower;
}

generateMatrixXML();

Footnote 1: Flash coding practises require you to define a new array with the [] notation:

var arr1:Array = []; // create a new array
var arr2:Array = [1]; // create an array with  one element, the number 1
var arr3:Array = new Array(1); // defines a new array with a pre-set length of 1
var arr4:Array = new Array(1,2); // defines a new array with two elements, the numbers 1 and 2

The last example is considered a bad coding practise in AS3 because of the confusion it causes with the third example.

Upvotes: 3

Related Questions