Select random element from a Javascript Array

Need to select a random element from a javascript array? The process is fairly straightforward but I was not clever enough to figure it out on my own. First take a random number with Math.random() [which will return a random number between 0 and 1] then multiply this number by the length of the array. You then need to use Math.floor to round the number down to the nearest whole number and voila… you have a random element number. All of this can be included in the square brackets of the array to make more condensed/easy to read code.

For Example

randomElement = testArray[Math.floor(Math.random()*testArray.length)];

 

 

Source: http://www.webmasterworld.com/forum91/2245.htm