I have an array that has sequential array keys and I need to randomly select one of the keys... what's the best way to do that?
Take the 2-minute tour
×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
Math.random() will generate a number between 0 and 1.
|
|||||||||||||
|
Have a look at JavaScript random() Method and Generating a random number in JavaScript |
|||
|
Only using the array length will result in never actually selecting the last item in the array, except in the extremely rare situation when the random number selected is 1.0000. Better to add .99999 to the arr.length:
|
|||||||||
|