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?
A generic way to get random element(s):
Simple Function :
OR
OR
You set a constant variable to the array, you then have another constant that chooses randomly between the three objects in the array and then the function simply returns the results.
This is similar to, but more general than, @Jacob Relkin's solution:
This is ES2015:
The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.
If you want to write it on one line, like Pascual's solution, another solution would be to write it using ES6's find function (based on the fact, that the probability of randomly selecting one out of
n
items is1/n
):Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers (
floor(random()*length
and using a seperate function) are your way to go.