Join the Discussion
You learned how to define boolean, numeric, and text (string) variables in an earlier tutorial and will by now have been using them for some time. You may even have found yourself defining a group of similar variables where you need a number of different values to choose between using if or case statements or to pass at different times to the same function.
We define an array object like this:
As you can see, we have defined an object (or variable) called myArray. Where this declaration differs from those we saw earlier is that equals sign is followed by the reserved word new which identifies that what follows is the constructor for a class, in this case we are calling the constructor for the Array() class.
So what exactly is a constructor? A constructor is a special method (function) attached to a class that defines how to create an object that belongs to that class. in this case the Array() method performs the processing necessary to create the object 'myArray'.
Since a method is like a function, we can pass parameters to it. Here we can pass any number of parameters to the Array() method to initialize the individual entries within the array like this:
'message two','message three');
Doing this has the effect of initializing the first three entries in the array (in this example) to the values passed. You can pass as many parameters as you need to define as many variables within the array as you require. If instead of text strings you specify numbers or true/false then the type of variables within the array will be numeric or boolean instead of string variables.
Accessing Array Entries
So now that we have created our array and perhaps assigned values to some of the entries within it, how do we access those entries? Well here we need to introduce a new operator ()that allows you to reference particular entries within the array. Entries within an array are numbered (starting with zero) and can be referenced by specifying the entry number between the brackets like this:
We can also assign values to individual entries within the array using the same operator like this:
Of course like the other objects that we looked at in the previous tutorial there are a number of other properties and methods available that you can use with arrays. One in particular that you may find useful is the length property which will return the number of entries in the array that have been assigned values.
Using What You Know
Using an array you no longer need to come up with separate names for each of a series of related variables, you just create an array and reference them within that. If you want to set up a number of different greetings like we did in the earlier tutorials about using case statements and passing parameters to functions, we can now do away with the case statement and use an array instead.
var greeting = new Array('Welcome','Merry Christmas',
'Happy New Year','Happy Easter','Happy Holidays');
if (m < 0 || m > greeting.length) m = 0;