
Arrays are used to organize a set of variables.
you could give every name its own variable. But it is easier to use arrays.
you tell x=New Array()...then give every name its own number
starting with 0
x[0]="Alexander";
x[1]="Beatrice"; and so on.
OK, it looks like a bit more typing is involved here, but there are some
advantages.
- You don't have to think of separate names for each value.
- It is now easier to track down and reference the values.
new Array prepares a section of cells. The number of cells is given
with in brackets. So the example is creating a section of 10 cells called
named
x.
The next step is filling in the values for the
x array. JavaScript is
very literal. It likes to start counting at 0. So entering the values for the
array must start at the 0 mark. And so forth down the array until all the
cells are filled.
Now give it a action. Have the visitor enter a number and then
have it print out the name that belongs to it.
<SCRIPT TYPE="text/javascript"><!--
var GetNumber=prompt("Enter a number between 1 and
10","");
var TrueNumber= GetNumber -1;
document.write(x[TrueNumber]);
// -->
</Script>
- A PROMPT box appears asking for a number between 1 and 10. This number
is placed in a cell named GetNumber. (If any other number is entered, the
result states undefined).
- A cell called TrueNumber holds the value of GetNumber minus 1. Again,
this is to get the correct cell reference as JavaScript starts counting at
0.
- The WRITE command then prints out the value for the stated array number.
click
and see script in action
Second example:
I searched around and finally found a
good use for a javascript with the array of images. I don't like the form
buttons, but all in all I think this is a pretty effect:
click and see script in action
index