Creating a large 2D array and filling it in AS3

I was wondering if there is a better way to create a large 2D array and populate it with one element with AS3? This is a quick example of what I'm doing now:

private var array:Array = [[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]; 

But there has to be a more functional way! Thanks in advance.

+4
source share
4 answers

Can't you just use the "traditional" loop to populate it? Something as simple as

 var numCols:uint = 10, numRows:uint = 10, fillValue:uint = 1, array:Array = new Array(), i:uint, j: uint; for (i = 0; i < numRows; i++) { array.push(new Array()); for (j = 0; j < numCols; j++) { array[i].push(fillValue); } } 
+11
source

I always use one dimensional array and write my own get / set functions to determine the location in the array for the point (x, y):

ie, Getting the item:

 return array[x+(y*_width)]; 

To reset the array or install it (after allocating it)

 for(var i:uint=0;i<array.length;i++) array[i] = 1; 

Basic moments:

  • You only need to select one array
  • You can reset or quickly set or copy items
  • I assume that flash uses “less” memory or less overhead since there is only one array.

On the one hand, make sure that the access and setter functions perform a range check, as your results may “work” but not be accurate. (Ie if x is wider but still within the array)

I "grew up" in C (language: -p), so this always seems like a logical way to do things; Select the memory block and split it the way you want.

+3
source

correct answer provided by kkyy ... although I would say classic, you should use i < numCols and j < numRows , so access is array[column][row] ...

also for greater performance:

 var numCols:uint = 10, numRows:uint = 10, fillValue:uint = 1, array:Array = new Array(), columnProto:Array = new Array(), i:uint; for (i = 0; i < numRows; i++) columnProto.push(fillValue); for (i = 0; i < numCols; i++) array.push(columnProto.slice()); 

leads to much less instructions ... but you will notice the difference when numCols * numRows much larger ...

+1
source
 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(); enter code here 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]); } } I hope this will b usefull for u.,... 
0
source

All Articles