Home >Web Front-end >JS Tutorial >How Can I Select a Random Element from a JavaScript Array?
Getting a Random Array Member with JavaScript
Selecting a random element from an array is a common task in JavaScript. Consider the following array:
var myArray = ['January', 'February', 'March'];
Solution
To retrieve a random array item, JavaScript offers a straightforward solution:
const randomElement = array[Math.floor(Math.random() * array.length)];
This line generates a random integer between 0 and array.length - 1, representing an index within the array. By accessing the array using this index, we retrieve a random element.
Example
Let's apply this solution to find a random month from the following array:
const months = ["January", "February", "March", "April", "May", "June", "July"];
Using the code:
const random = Math.floor(Math.random() * months.length); console.log(random, months[random]);
This code generates a random index (e.g., 3) and prints the corresponding month (e.g., "April"). Console output:
3 April
The above is the detailed content of How Can I Select a Random Element from a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!