Reputation: 513
I'm in need of creating multiple dynamic arrays and seem to have found exactly what I need at https://jadendreamer.wordpress.com/2012/05/06/flash-as3-tutorial-how-to-create-2d-or-3d-dynamic-multi-dimensional-arrays/
Example 1:
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]);
}
}
However, when testing either of the snippets provided at the site I end up with error "#1056: Cannot create property 0 on Boolean."
"Automatically declare stage instances
" is checked.
I've spent hours on this and I'm sure it's something simple, but I can't quite get it. Any suggestions?
Upvotes: 1
Views: 11955
Reputation: 2228
You have forgot to register the row array.
boolArray[row] = new Array();
For example, If you want to create an 1*3 array code the below.
var a:Array = new Array();
a[0] = new Array();
a[0][0] = '1';
a[0][1] = '2';
a[0][2] = '3';
To know the Basics of Multi dimensional array click here
Upvotes: 0
Reputation:
Remove boolArray
from the top, currently you're always adding the same Array to your 2D-Array, I doubt this is intentional.
var multiDimensionalArray:Array = new Array();
//var boolArray:Array; //remove this line
var MAX_ROWS = 5;
var MAX_COLS = 5;
//initalize the arrays
for (var row = 0; row <= MAX_ROWS; row++)
{
var boolArray:Array = new Array(); //create a new Array here
for (var col = 0; col <= MAX_COLS; col++)
boolArray.push(false);
}
multiDimensionalArray.push(boolArray);
}
This won't solve your problem though, but it will prevent further problems.
To solve your problem you need to look at your second for loop structure, at the bottom of the snippet.
Currently, you're trying to access boolArray[row][col]
. But this Object is not a 2D Array, it's a 1D Array. So you take the object at the index row
, then try to change the value of the variable that has the name of the value of col
, i.e. 0. As you are aware, Boolean doesn't have a variable called 0.
To put it simply, what you're doing here:
boolArray[row][col] = true
is actually
boolArray[row].0 = true
or
boolArray[row]["0"] = true
To solve this, you should refer to your actual 2D Array.
for (var row = 0; row <= MAX_ROWS; row++)
{
for (var col = 0; col <= MAX_COLS; col++)
multiDimensionalArray[row][col] = true;
trace('multiDimensionalArray' + row + ',' + col + ' = ' + multiDimensionalArray[row][col]);
}
}
To sum it all up in one sentence: You used the wrong Array Object.
Upvotes: 1