An Introduction To JavaScript Arrays

Apr 25, 2008 15:48 GMT  ·  By

Random events control will always be a challenge for any webmaster. Depending on the event type, there are various coding options to produce a random action as output of a script. The manipulation of random web content can be performed from within any server side or client side programming language.

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:

code
function randompage()
{
var arrindex=Math.floor(Math.random()*4)
var webpages=new Array(4)
webpages[0]="http://www.google.com"
webpages[1]="http://www.softpedia.com"
webpages[2]="http://webscripts.softpedia.com"
webpages[3]="https://news.softpedia.com"
window.open(webpages[arrindex])
}
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.