Skip to main content
Inspiring
July 11, 2014
Answered

AS3 Multidimensional Array

  • July 11, 2014
  • 1 reply
  • 791 views

Hi.

I'm new to AS3. I would like to know how can I create a multidimensional array (eg. 8x8) using for or while. The values in it must be only: red, blue, green, yellow and black.

Thanks.

This topic has been closed for replies.
Correct answer Ned Murphy

If you want to pick the colors randomly, place them in an array and randomly pick one of them by using the Math methods...

var colorArray:Array = new Array("red", "blue", etc...)

for(var i:int=0; i<8; i++){

  mArray = new Array();

    for(var k:int=0; k<8; k++){

          mArray.push(colorArray[Math.floor(Math.random()*colorArray.length)]);

    }

}

1 reply

Ned Murphy
Legend
July 11, 2014

You will need to use two loops if you want a 2 dimensional array, one nested inside the other.  The first loop will create the individual arrays and the second will assign the elements to each.

var mArray:Array = new Array();

for(var i:int=0; i<8; i++){

    mArray = new Array();

    for(var k:int=0; k<8; k++){

          mArray.push(whichever color you intend);

    }

}

gibsyAuthor
Inspiring
July 11, 2014

Thanks. It helped me a lot. I would like to choose the colours randomely.

Ned Murphy
Ned MurphyCorrect answer
Legend
July 11, 2014

If you want to pick the colors randomly, place them in an array and randomly pick one of them by using the Math methods...

var colorArray:Array = new Array("red", "blue", etc...)

for(var i:int=0; i<8; i++){

  mArray = new Array();

    for(var k:int=0; k<8; k++){

          mArray.push(colorArray[Math.floor(Math.random()*colorArray.length)]);

    }

}