Mega Code Archive

 
Categories / JavaScript Tutorial / Array
 

Reference array element by random index value

< html> <head> <title>Example</title> </head> <body> <script type="text/javascript"> function selectFrom(iFirstValue, iLastValue) {     var iChoices = iLastValue - iFirstValue + 1;     return Math.floor(Math.random() * iChoices + iFirstValue); } var aColors = ["A", "B", "C", "D", "E", "F", "G"]; var index = selectFrom(0, aColors.length-1); var sColor = aColors[index]; alert(sColor); </script> </body> </html>