Consider:
var myArray = ['January', 'February', 'March'];
How can I select a random value from this array using JavaScript?
Consider:
var myArray = ['January', 'February', 'March'];
How can I select a random value from this array using JavaScript?
Create one random value and pass to array
Please try following code..
I've found it even simpler to add a prototype function to the Array class:
Now I can get a random array element by just typing:
Note that this will add a property to all arrays, so if you're looping over one using
for..in
you should use.hasOwnProperty()
:(That may or may not be a hassle for you.)
The shortest version:
In my opinion, better than messing around with prototypes , or declaring it just in time, I prefer exposing it to window:
Now anywhere on your app you call it like:
This way you can still use
for(x in array)
loop properlyvar item = myArray[Math.floor(Math.random()*myArray.length)];
or equivalent shorter version:
var item = myArray[(Math.random()*myArray.length)|0];
Sample code: