Free Javascript Tutorials

home

JavaScript Tutorials

Arrays (contined)

 
Our quick javascript links
Little Programmes
 
 
 
 
 
 

 

The index number of an array

 

Arrays really come in to their own when you access their index numbers. You can use a variable in place of the index number. Then, if you increment the variable, you can access the elements in your array. As an example, try this script in a web page. For the web page, create a form called frmOne. Put a button on the form, and a text box called txtSeason. If you prefer, copy and paste this one:

<FORM name = frmOne>

<INPUT Type = text name = txtData>
<INPUT Type = button value = " Seasons " onClick = GetSeasons()>

</FORM>

When you've got the form in place, add this script to the HEAD section of your code:

<SCRIPT language=JavaScript>

inc = 0

function GetSeasons () {

Seasons = new Array(3)
Seasons[0] = "Winter"
Seasons[1] = "Spring"
Seasons[2] = "Summer"
Seasons[3] = "Autumn"

document.frmOne.txtData.value = Seasons[inc]

inc++
}

</SCRIPT>

We're setting up the array in exactly the same way. Now, though, we're calling a function with the onClick event of the button in the Form:

onClick = GetSeasons()

The function will set up the array. It also puts a value in our text box. But note what the value is - it's one of our elements in the array. But which element is it?

document.frmOne.txtData.value = Seasons[inc]

The inc is a variable. It was set up outside the function, making it global (all your functions can see a global variable):

inc = 0

So the first value put into our text box is this:

document.frmOne.txtData.value = Seasons[0]

In the final line of the code, we then increment the variable:

inc++

So every time the button is clicked, 1 will get added to the inc variable. The next time you click the button, the code is really this:

document.frmOne.txtData.value = Seasons[1]

When the value in the inc variable goes above 3, you'll get this in the text box:

undefined

That's because we don't have a position number 4 in our array. You can reset the inc variable like this:

if (inc > 3) inc = 0

That should prevent "undefined" from displaying in the text box.

Arrays are used a lot inside loops. We're going to see how that works now by creating a lottery number generator. But before continuing you should ensure that you have a good understanding of how for loops work. If not, go back and revise.

In the next part, we'll start work on a lottery programme.

Move on to the Next Part -->

<--Back to the JavaScript Contents Page