Arrays

Example 1: Creating Arrays

When you create an Array, you are said to be declaring the array. In this example a new array is created using the variable day and it will contain seven elements

var day = new Array(7)

You are not required to put a number in the Array keyword. There are many times when you won’t know how many elements there will be in an array, so you can always just create an empty array and populate it, as and when you need to. For example

var day = new Array()

Example 2: Populate the array

When you first declare an array you can populate each element or you can populate an array at any time. The array name is suffixed with a square bracket containing the element number. In practice with standard programming, arrays start with 0 as the first element. For example:

day[0] = "Sunday"
day[1] = "Monday"
day[2] = "Tuesday"
day[3] = "Wednesday"
day[4] = "Thursday"
day[5] = "Friday"
day[6] = "Saturday"

Example 3: Populate an array with a loop

A common method of populating an array is by using a loop. For example:

dollars = new Array()
sterling = new Array()
sterling[1] = 23
sterling[2] = 17.50
sterling[3] = 75
var exchangeRate = 1.70
var loopCounter = 1
while (loopCounter <= 3)
{
 dollars[loopCounter] = sterling[loopCounter] * exchangeRate
 loopCounter++
}

In the example above, the array named sterling is multiplied by the value of exchangeRate and the calculated result stored in an empty array named dollars. Notice that the element number can be a variable (as long as the variable is a number). The first time the while loop is executed the variable loopCounter is 1, therefore the element sterling[1] is multiplied by exchangeRate (i.e. 23 multiplied by 1.70) and the calculated result stored in the element dollars[1].

Example 4: Using an element in a statement

Each element in an array is like a variable, it can contain any of the Data Types, such as a string, a number or a Boolean value. As a result elements are often used in other lines of codes in your program

var days = new Array()
days[0] = "Sunday"
var firstDay = days[0]
var checkDay = "Sunday"
if (checkDay == days[0])
{
 sundayImage.Show()
}

The third line in Example 4 above stores the value of element days[0] to a new variable named firstDay (i.e. firstDay now contains the value "Sunday"). In line 4, the variable checkDay is set to the string "Sunday" and the if expression checks if the variable checkDay and the element days[0] contain the same data, if they do the Image object named sundayImage is displayed on the page.

Close