Is there any way to create instances of array in a for loop?
Here's my code...
var recArrCon1:Array = new Array(50);
var recArrCon2:Array = new Array(50);
var recArrCon3:Array = new Array(50);
var recArrCon4:Array = new Array(50);
var recArrCon5:Array = new Array(50);
var recArrCon6:Array = new Array(50);
var recArrCon7:Array = new Array(50);
var recArrCon8:Array = new Array(50);
I want to make declaration in a dynamic way by a for loop. Thanks in advance.
By the way, I'm using AS3
Edit: The answer is (from Barış Uşaklı):
var recArrCons:Object = {};
for(var i:int=1; i<=8; i++)
{
recArrCons["recArrCon" + i] = new Array(50);
}
trace(recArrCons.recArrCon4); // 4th array
-
What language are we talking about?Chief Wiggum– Chief Wiggum2013年05月15日 01:36:50 +00:00Commented May 15, 2013 at 1:36
2 Answers 2
Make the class containing this code dynamic then you can create the names dynamically.
for(var i:int=1; i<=8; i++)
{
this["recArrCon" + i] = new Array(50);
}
trace(this.recArrCon4); // 4th array
Or you can store them in an Object
like :
var recArrCons:Object = {};
for(var i:int=1; i<=8; i++)
{
recArrCons["recArrCon" + i] = new Array(50);
}
trace(recArrCons.recArrCon4); // 4th array
5 Comments
dynamic
recArrCons['recArrCon'+ firstPName][i]
will give the ith
element. It will be much more readable if you store a reference to the array though like : var arr:Array = recArrCons['recArrCon'+firstPName]
and ten arr[i]
I wouldn't create instances of Array the way you are, it's very messy. I suggest using a list of arrays like this:
var arrays:Vector.<Array> = new <Array>[];
for(var i = 0; i < 8; i++)
{
arrays.push(new Array(50));
}
Where you would access an array like this:
var inner:Array = arrays[2];
And values of the arrays using [x][y]
:
trace(arrays[0][0]);
2 Comments
Explore related questions
See similar questions with these tags.