Advertisement |
Creating arrays
Arrays are objects. As such, they must be instantiated and assigned to reference variables. Then you use the reference variable and dot syntax to access an array's properties, methods, and elements. The following code instantiates an empty array:
var myArray:Array = new Array();
All ActionScript 3 arrays have a length property. That length property corresponds to the number of elements stored in the array at any given time. Executing the code below will show that the array currently has 0 elements.
var myArray:Array = new Array();
trace(myArray.length); //0
Once in a while you will know the number of elements needed for an array before you create it. For example, if you were going to create an array to hold every day of the week, you would know that
the array only needs to hold seven elements. You would instantiate an array, passing it an integer to specify the number of elements.
the array only needs to hold seven elements. You would instantiate an array, passing it an integer to specify the number of elements.
var days:Array = new Array( 7 );
trace(days.length); //7
The code above creates an array with seven places to be defined in the future. It can be helpful to think of an array as having a number of slots (or indexes) that hold each piece of data. So, an array
of seven items could be visualized as:
of seven items could be visualized as:
Although data is usually added to arrays after they are created, it is possible to instantiate an array with initial elements.
var days:Array = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
trace( days.length ); //7
If you only provide one value, and the value is a number, it is interpreted as a length.
Finally, it is possible to instantiate an array by assigning it a literal value using a special shortcut syntax. In ActionScript 3 square brackets [ ] are often associated with arrays.
var days:Array = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
trace( days.length ); //7
You can create an empty array in the following way:
var elements:Array = [];
Regardless of which way you create or populate the array, you will end up with an identical data structure containing your values.
Data can be added and removed from ActionScript 3 arrays at runtime. You can replace existing array elements or shrink or grow the array as needed. There are a number of methods available in
the Array class to manipulate data in an array, but only the most commonly used methods will be discussed here.
the Array class to manipulate data in an array, but only the most commonly used methods will be discussed here.
push() and pop() methods
The first method is the push() method of the Array class. The push() method adds one or more new elements to the end of an array. The method returns the new length of the array after the new item(s) have been added.
var letters:Array = new Array()
letters.push( "C" );
letters.push( "D", "E", "F" );
var lettersArrayLength:uint = letters.push( "G" );
trace(lettersArrayLength); //5
trace(letters.length); //5
Items can be removed from the end of an array with the pop() method. The pop() method removes one element from the end of an array and returns it. Look at the following example:
var letters:Array = new Array();
letters.push( "C" );
letters.push( "D" );
var letter:String = letters.pop();
trace(letter); //D
letters.push( "E" );
trace(letters); //C, E
For those of you familiar with a Stack data structure, the push() and pop() methods provide an easy way to implement it using an array in ActionScript 3.
Index
While adding data with push() and removing it with pop() is an effective way to manipulate the end of an array, arrays are most commonly manipulated and accessed via index. In ActionScript 3, an array's index begins at 0, meaning the first element of the array is the 0th element.
Individual values of the array are accessed by using the name of the array, followed by square brackets and the index you wish to retrieve. For example:
var days:Array = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
trace(days[1]); //Mon
You can think about the array in the code above as looking like this:
You can also use this same technique to modify the contents of an Array. For example, you could modify the string 'Thu' to say 'Hi".
var days:Array = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
days[4] = "Hi";
Because array indexes are 0-based, the last element of the array is always one less than the length. That means if you have an array of length 7, then the last element of the array is at index 6.
You can also use the index to populate data, just as you did with the push() method.
var days:Array = new Array();
days[ 0 ] = "Sun";
days[ 1 ] = "Mon";
shift() unshift() and splice() methods
Elements can also be removed from the beginning of an array with the shift() method. By using shift(), you can use an array as a queue. The shift() method removes the element from the
first indexed location and returns it. The remaining elements are moved from their original index location i to i-1
first indexed location and returns it. The remaining elements are moved from their original index location i to i-1
var queueArray:Array = new Array("one", "two", "three", "four");
var wasInArray:String = queueArray.shift();
trace(wasInArray); //one
trace(queueArray); //two, three, four
You can also add elements to the beginning of an array using the unshift(…args) method. The remaining elements are moved from their original index location of i to i+1
var arrayToUnshift:Array = new Array("three", "four");
arrayToUnshift.unshift("two");
trace(arrayToUnshift); // two, three, four
arrayToUnshift.unshift("zero", "one");
trace(arrayToUnshift); //zero, one, two, three, four
Finally, the splice() method allows you to insert data into or remove data from an array at someplace other than the first or last index locations. When using splice() to add data, elements are moved within the array to make room for the inserted data. When using splice() to remove data, elements
are moved to fill in the empty space left after removal. When you call the splice() method, you specify three arguments:
are moved to fill in the empty space left after removal. When you call the splice() method, you specify three arguments:
- the index location to insert data into
- how many (if any) elements to the right of the insertion index should be deleted
- data to be inserted (optional)
var spliceArray:Array = ["do", "re", "fa", "fa", "so", "la", "ti", "do"];
spliceArray.splice(2, 0, "mi");
trace(spliceArray); // do, re, mi, fa, fa, so, la, ti, do
spliceArray.splice(4, 1);
trace(spliceArray); // do, re, mi, fa, so, la, ti, do
You can sort the data in an array. By default the sort() method is ascending (a-z), case sensitive (Z comes before a), and treats all data as strings. Treating all data as strings means that numerical data will be incorrectly sorted—100 will come before 4.
You can pass the sort method arguments to affect how it sorts.
Array.CASEINSENSITIVE
Array.DESCENDING
Array.UNIQUESORT - throws a false if two elements are identical
Array.RETURNINDEXEDARRAY
Array.NUMERIC
Look at how array data is sorted in the examples below.
var stringArrayToSort:Array = new Array("apple", "Zebra", "Orange", "raspberry",
"blueberry");
stringArray.sort();
trace(stringArrayToSort); // Orange, Zebra, apple, blueberry, raspberry
stringArrayToSort.sort(Array.DESCENDING);
trace(stringArrayToSort); // raspberry, blueberry, apple, Zebra, Orange
stringArrayToSort.sort(Array.CASEINSENSITIVE);
trace(stringArrayToSort); //apple, blueberry, Orange, raspberry, Zebra
var numberArray:Array = [4, 59, 100, 12, 38];
numberArray.sort();
trace(numberArray); //100, 12, 38, 4, 59
numberArray.sort(Array.NUMERIC);
trace(numberArray); //4, 12, 38, 59, 100
For more advanced sorting or sorting of complex arrays you can either write a function to help the
sort() method or use the sortOn() method.
So far all of the arrays you have seen in this article have been homogenous in that they have contained the same type of data in every element of the Array. This is fairly common; however, it is not a requirement of ActionScript 3 arrays. It is perfectly legal to add elements of varied types to an array. The code below creates a heterogeneous array.
var elements:Array = ["Hello", 1.23, new Date()];
Up to this point, the arrays in this article can be referred to as dense arrays. This means that every element has some form of value present. ActionScript 3 also supports sparse arrays. Sparse arrays have missing elements. The code below creates a sparse array, as illustrated by the graphic that follows it.
var elements:Array = new Array();
elements[ 0 ] = "A";
elements[ 1 ] = "B";
elements[ 3 ] = "C";
elements[ 4 ] = "D";
elements[ 6 ] = "E";
Note that there are elements at indexes 0,1,3,4 and 6. The other positions do not exist in this array.
If you were to execute the following line of code on this array:
If you were to execute the following line of code on this array:
trace(elements[ 2 ]); //undefined
you would receive an undefined as your output. Sparse arrays can be very convenient. However,
it is important to note that sparse arrays are significantly slower at runtime. They lack the significant optimization that the Flash Player can provide to regular arrays which are in a simple fixed order.
it is important to note that sparse arrays are significantly slower at runtime. They lack the significant optimization that the Flash Player can provide to regular arrays which are in a simple fixed order.
Also note that this is different than an array with null values:
var elements:Array = new Array();
elements[ 0 ] = "A";
elements[ 1 ] = "B";
elements[ 2 ] = null;
elements[ 3 ] = "C";
elements[ 4 ] = "D";
elements[ 5 ] = null;
elements[ 6 ] = "E";
When you insert null into indexes 2 and 5 you are creating an array with all 7 positions defined. Two of those 'slots' simply contain a null value. An array with null values is a dense array, not a sparse one.
If you have a sparse array (at least one missing index) and you later fill in each of those missing indexes, Flash Player will begin to treat it as a dense array and the performance will improve.
You can add any type of object into an ActionScript 3 array, including more arrays. The following code creates a new Array, and for each element, adds a new Array. In this example the [] syntax is used to create new Arrays.
var elements:Array = [];
elements[ 0 ] = [ "A", "B", "C" ];
elements[ 1 ] = [ "D", "E", "F" ];
elements[ 3 ] = [ "G", "H", "I" ];
trace( elements[ 0 ][ 0 ] ); //A
As you can see, the resultant memory structure can be thought of more like a two-dimensional table and elements are accessed using two sets of square brackets.
trace( elements[ 0 ][ 0 ] ); //A
It is possible to nest arrays inside each of these array elements, making three-dimensional (or more) arrays. That practice isn't used very often; however, it is useful to know the capabilities of the language for the times when it might be useful.
Using loops with arrays is one of the most common practices in programming. The iteration variable in a for loop can serve as the index for an array, making it easy to iterate through every element in the array. In the code below, the loop will cause the element at each index to be traced.
var musicArray:Array = new Array("do", "re", "mi", "fa", "so");
for (var i:int = 0; i<musicArray.length; i++) {
trace(musicArray [i]);
}
//output
do
re
mi
fa
so
The example below demonstrates that you can use a loop to alter each element in an array.
var numberArray:Array = [5, 10, 15, 20, 25];
trace(numberArray);
for (var j:int = 0; j< numberArray.length; j++){
numberArray [j]+=2;
}
trace(numberArray);
//output of first trace()
5
10
15
20
25
//output of second trace()
7
12
17
22
27
You can also iterate through the elements of an array and search for a given value. The function below shows how you can move through an array element by element and check its value. If the function finds the value, it returns the index of the element in the array. If it fails to find the value,
it returns a -1.
it returns a -1.
function findIndexOfValue( array:Array, value:* ):int {
var length:uint = array.length;
for(var i:uint=0; i<length; i++) {
if(array[i] == value){
return i;
}
else{
return -1;
}
}
}
var elements:Array = [];
elements[ 0 ] = [ "A" ];
elements[ 1 ] = [ "B" ];
elements[ 2 ] = [ "C" ];
trace(findIndexOfValue(elements, "C")); //2
trace(findIndexOfValue(elements, "Z")); //-1
0 comments: