patternjavascriptCritical
Getting a random value from a JavaScript array
Viewed 0 times
arrayfromrandomgettingvaluejavascript
Problem
Consider:
How can I select a random value from this array using JavaScript?
var myArray = ['January', 'February', 'March'];How can I select a random value from this array using JavaScript?
Solution
It's a simple one-liner:
For example:
const randomElement = array[Math.floor(Math.random() * array.length)];For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);Code Snippets
const randomElement = array[Math.floor(Math.random() * array.length)];Context
Stack Overflow Q#4550505, score: 2366
Revisions (0)
No revisions yet.