Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I choose a random value from an array with JavaScript? [duplicate]

Tags:

javascript

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?

like image 385
don3434 Avatar asked Apr 18 '11 20:04

don3434


People also ask

How do you select a random number in JavaScript?

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.

How do you assign a random number to an array?

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.


1 Answers


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)

like image 122
locrizak Avatar answered Sep 18 '22 05:09

locrizak