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
Release: 2024-12-27 15:36:10
Original
169 people have browsed it

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'];
Copy after login

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)];
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template