Reputation: 62504
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?
Upvotes: 9
Views: 9654
Reputation: 1
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:
var key = Math.floor(Math.random() * (arr.length + .999999))
Upvotes: -18
Reputation: 166626
Have a look at JavaScript random() Method and Generating a random number in JavaScript
Upvotes: 2
Reputation: 11661
Math.random() will generate a number between 0 and 1.
var key = Math.floor(Math.random() * arr.length);
Upvotes: 21