Home >Web Front-end >JS Tutorial >How to Select a Random Value from a JavaScript Array?

How to Select a Random Value from a JavaScript Array?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 15:36:10179browse

How to Select a Random Value from a JavaScript Array?

Selecting Random Values from JavaScript Arrays

Consider an array of strings:

var myArray = ['January', 'February', 'March'];

How do you retrieve a random value from this array using JavaScript?

Solution

The answer lies in a simple one-liner:

const randomElement = array[Math.floor(Math.random() * array.length)];

The Math.random() function generates a random decimal value between 0 and 1 (exclusive). Multiplying this by the array's length and using Math.floor() ensures an integer index within the array's bounds.

For example:

const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]); // Output: 3 April

This snippet generates a random index between 0 and 6, and outputs the corresponding value from the months array.

The above is the detailed content of How to Select a Random Value from a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn