How to select a random value from an array with JavaScript?

Possible duplicate:
JavaScript: getting a random value from an array

I have external js with the following line:

var postmessage = "hi my favorite site is http://google.com"; 

but is there a way to select a site randomly from an array, so

 var postmessage = "hi my favorite site is +'random'"; random= http://google.com, http://yahoo.com, http://msn.com, http://apple.com 

how can i make it work?

+6
source share
3 answers
 var favorites = ["http://google.com", "http://yahoo.com", "http://msn.com", "http://apple.com"]; var favorite = favorites[Math.floor(Math.random() * favorites.length)]; var postmessage = "hi my favorite site is " + favorite; 

Create an array of your sites, then select one element from the array. You do this by choosing a random number using Math.random() , which gives a result greater than or equal to 0 and less than 1. Multiply by the length of your array and take floor (i.e. take only the integer part, omitting any decimal points) so that you will have a number from 0 to one less than the length of your array (which will thus be a valid index in your array). Use this result to select an element from your array.

+20
source
 var sites = new Array('http://www.google.com', "http://www.stackoverflow.com") var postmessage = "hi my favorite site is" + sites[Math.round(Math.random()*(sites.length-1))];
var sites = new Array('http://www.google.com', "http://www.stackoverflow.com") var postmessage = "hi my favorite site is" + sites[Math.round(Math.random()*(sites.length-1))]; 

First, collect all your sites in an array. Then get a random number from the length of the array (-1 - this is because the array is null index and the returned length starts at 1)

+3
source

Do something like this:

 function getRandomSite(){ var sites = ["google.com","bing.com","xyz.com","abc.com","example.com"]; var i = parseInt(Math.random()*(sites.length-1)); return sites[i]; }; 
+1
source

Source: https://habr.com/ru/post/886184/


All Articles