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?
Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.
In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With