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
This line:
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 AS31You actually need to create your arrays within the loop:
Footnote 1: Flash coding practises require you to define a new array with the
[]notation:The last example is considered a bad coding practise in AS3 because of the confusion it causes with the third example.