How do I choose a random value from an array with JavaScript? [duplicate]
Possible Duplicate:
JavaScript: Getting random value from an array
I have an external js with the following line:
var postmessage = "hi my favorite site is http://google.com";
but is there a way to pick a site a random from an array so like this
var postmessage = "hi my favorite site is +'random'";
random= http://google.com, http://yahoo.com, http://msn.com, http://apple.com
how do i make it work?
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 pick one element from the array. You do this by choosing a random number using Math.random()
, which gives you a result greater than or equal to 0 and less than 1. Multiply by the length of your array, and take the floor (that is, take just the integer part, dropping off any decimal points), so you will have a number from 0 to one less than the length of your array (which will thus be a valid index into your array). Use that result to pick an element from your array.
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 stick all of your sites in an array. Then get a random number from the array length (the -1 is because an array is zero indexed and the length that is returned starts at 1)
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];
};
精彩评论