In an earlier tutorial I talked about variables, now we are going to take a look at arrays. The definition of arrays could be "variables on steroids". Let's take a closer look:
If a variable is a box that you can fill with strings and numbers the array is a box with a number of slots. Each slot can contain a value or a string.
Just like with variables we need to declare the array. The declaration is a bit different, we create a new instance of the array object, but you don't have to know anything about that right now! :-)
var myArray=new Array()
That's it! Now we can start filling the slots:
myArray[4]="Peter Forsberg"
The statement above will store the string "Peter Forsberg" in the 5th slot. The 5th? It says 4 in the script?! JavaScript always starts counting at 0, so the string is actually in the 5th slot.
Just like with variables we can assign values at the time we create the array, like this:
var myArray=new Array("Peter Forsberg",257,"Björn Borg","Kenny Brack",9675)
It's possible to mix strings and values in the same array, like in the example above.
You have probably figured out that things become much more organized with arrays, but the best thing with arrays is that you can use a loop to search for something that is stored in the array. We'll look into that in the tutorial on loops.
You should also know that JavaScript uses a lot of arrays internally. Maybe you remember document.all["layer1"].style.visibility="hidden" from the DOM tutorial? The brackets "[ ]" tells us that "document.all" is an array, but this array doesn't use numbers to labels the slots, it uses strings, in this case "layer1".
Another example of internal arrays is the document.forms array. If you have two forms in a page the first form will be document.forms[0] and the second document.forms[1] . This means that you don't have to know the name of the form, you can use the internal array instead.
Bottom line...
- Arrays are containers with a number of slots.
- Each slot can contain a variable, an object or another array.
- The slots can be labelled with a number or with a text string.
- We can use a loop to check every slot in the array, or just some.
Back to tutorial index <<
|