Contact ZenDuo


Actionscript 2 Shuffle an Array



Using arrays in flash is always a handy and efficient way to work with variables etc. But some times its handy to be able to shuffle the results in the array, for example when creating a quiz to allow a random set of questions.

Using the code below (actionscript 2.0 but should still work in 3.0) we create an array and trace the results.

The Code

Array.prototype.shuffle=function(){
   for(i=0;i<this.length;i++){
      var tempvar=this[i];
      var ranVar=random(this.length);
      this[i]=this[ranVar];
      this[ranVar]=tempvar;
   }
}

myArray=["flash","dreamweaver","illustrator","in-design","photoshop"];
myArray.shuffle();
trace(myArray);

This would return a trace with answers such as:
‘dreamweaver, flash, in-design, photoshop, illustrator’

This entry was posted on Monday, September 28th, 2009 at 7:28 pm and is filed under ActionScript & Flash. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply