JavaScript Arrays: Random Webpage URLs

When you want to create a random navigation system that allows to open windows corresponding to different URLs, the simplest method is provided by a Javascript array implementation in a quick script. The array represent a form of storage of multiple values in a single variable. By declaring variables values in an array there is […]

When you want to create a random navigation system that allows to open windows corresponding to different URLs, the simplest method is provided by a Javascript array implementation in a quick script. The array represent a form of storage of multiple values in a single variable. By declaring variables values in an array there is no need to define a unique name for every variable. You can refer to a certain value contained in array by using its index.

Lets consider the next JavaScript example that will open a new browser window with a random webpage URL contained in an array:

<html> <head> <script language="JavaScript"> function randompage() { var arrindex=Math.floor(Math.random()*4) var webpages=new Array(4) webpages[0]="http://anshugpta.blogspot.com/" webpages[1]="http://yourhealthinformation.blogspot.com/" webpages[2]="http://www.ditii.com" webpages[3]="http://anscreativity.blogspot.com" window.open(webpages[arrindex]) } </script> </head> <body> <input type="button" value="Random Page" onclick="randompage()"> </body> </html>

The line 7 uses the Array() function to declare the webpages array that will contain four elements. The next four lines defines the array elements (the pages URLs). By using the Array() function used without argument allows the insertion of undefined number of elements in the array. The arrindex variable value is randomly generated in the line 6: it will be an integer number situated in the range 0 and 3 because the generated numbers are rounded to the lower value of the closest integer in the range 0 and 3.99.

When the button called Random Page is pushed the randompage() function is called, a random number is generated and based on its value, the array index corresponding to a certain URL is established and in the new browser window opened the web page is shown. The script can be customized in various ways.You can add other URLs by increasing the number of array elements or the script can be adapted to show random content in web pages, such as random quotes.

Source:→ Softpedia

JavaScript, Array, Random Webpages, URL