If your array was named arr
, you could easily retrieve a random value with this code snippet:
var value = arr[Math.floor(Math.random() * arr.length)];
This code will generate a random number within the range of 0 to the length of your array.
You can then direct the user to the generated URL using the following JavaScript:
window.location = value;
Testing out the Code
We have created a simple demonstration on JSFiddle: http://jsfiddle.net/ESSAc/1/
In the demo, there is a button with an onclick attribute that executes the function when clicked:
<input type="button" onclick="runme()" value="Click Me!" />
The function defined in the script randomly selects a URL from an array and displays it in an alert box:
function runme() {
var arr = ["http://www.bbc.co.uk/", "http://www.yahoo.com/", "http://www.stackoverflow.com/"];
var value = arr[Math.floor(Math.random() * arr.length)];
alert("Would navigate to : " + value);
// window.location = value; // Uncomment this line to actually navigate
}