Q:

How to Get a Random Item from a JavaScript Array

0

How to Get a Random Item from a JavaScript Array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the Math.random() Method

You can simply use the Math.random() method in combination with the Math.floor() method to get a random item or value from an array in JavaScript.

The Math.random() method returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1), whereas the Math.floor() method round the number down to the nearest integer. Let's try out an example to understand how it actually works:

// Sample array
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

// Getting a random value
var randomItem = days[Math.floor(Math.random() * days.length)];

console.log(randomItem);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Format JavaScript Date as YYYY-MM-DD... >>
<< How to Check If an Array Exists and Not Empty in J...