Have you ever had a bunch of variables that have a lot in common? For example, do you have variables such as name_1, name_2, name_3, name_4, and so on? These variables look like lists of common information, such as:
var name_1:String = "Peng"; var name_2:String = "Django"; var name_3:String = "Jenn"; var name_4:String = "Frank";
In programming languages, an array is a list of values that can be addressed by their position in the list. An array is created by using the Array constructor:
var visitors:Array = new Array();
The preceding code object simply creates the array container for data. You create an array with information already specified, such as:
var visitors:Array = new Array("Peng"," Django"," Jenn"," Frank");
or
var visitors:Array = ["Peng", "Django", "Jenn", "Frank"];
To access an item in visitors, you would use the array access operators with an array index number. To access the first position's data, you would use the following code:
var message:String = "Hello "+ visitors[0] + ", and welcome.";
Here, visitors[0] will return the value "Peng". If you traced the message variable, it would read:
In most programming languages, the first index value (the starting position) is 0, not 1. In the following table, you'll see how the index number increases with the sample visitors array.
Index Position |
0 |
1 |
2 |
3 |
---|---|---|---|---|
Index Value |
Peng |
Django |
Jenn |
Frank |
You can set and get the values within an array using the array access operators. You can replace existing array values by setting the index position to a new value, and you can add values to the array by increasing the index number, as in:
var visitors:Array = new Array("Peng"," Django"," Jenn"," Frank"); visitors[3] = "Nicole"; visitors[4] = "Candice";
In the example, "Nicole" replaces "Frank", and "Candice" is added to the end of the array. You can also add elements to the array using the push() method of the Array class, as in:
var visitors:Array = new Array("Peng"," Django"," Jenn"," Frank"); var nLength:Number = visitors.push("Nicole"," Candice");
This code will add "Nicole" and "Candice" after "Frank", and set the variable nLength equal to the length of the visitors array. length is an Array property that returns the number of elements in the array. In the preceding example, nLength is equal to 6 because there are now six names in the array.