Wednesday 28 November 2012

Arrays in action script 3.0



An array is a collection of pieces of data all of the same type (typically, but the compiler doesn't check for that) that are accessible by a numeric index. For example, the strings "cse", "eee", and "ece" might all be stored in an array named btech_courses, and if stored in that order, the first element would be accessible as btech_courses[0] (the indexing always starts with 0) and the last would be btech_courses[2].
var btech_courses:Array = ["cse", "eee", "ece"];
trace('the first element is ' + btech_courses[0] + ' and the last element is ' + btech_courses[2]);
Pasting that code into a Flash movie and ruuning it produces this in the Output panel: the first element is cse and the last element is ece. Like the String class, the Array class has several methods that are indispensable for manipulating arrays. Here's an example sequence of array statements, with the output from each: 

Operation
Result of trace statement
Create a 3-element array of information sources:
var sources:Array;
sources = new Array("google","about","altavista");
trace("sources has " + sources.length + " elements");
or, the abbreviated way (note the square brackets):
var sources:Array = ["google", "about", "altavista"];
sources has 3 elements
Use push method to add another element at the end of the array
sources.push("metacrawler");
trace(sources);
google,about,altavista,metacrawler

(Note that running a trace on an array causes all elements to be dumped out as strings, one at a time, separated by commas)
Use reverse method to reverse order of array
sources.reverse();
trace("first element is now " + sources[0]);
first element is now metacrawler
pop the array to remove the last element
sources.pop();
trace(sources);
metacrawler,altavista,about
Use splice to insert elements in the middle of the array
sources.splice(2, 0, "atomz", "lycos");
trace(sources);
metacrawler,altavista,atomz,lycos,about

The 2 specifies that splicing will begin at the third element of the array; the 0 specifies that no elements are to be deleted (since splicing can be used either for adding elements to or deleting elements from an array); the last two parameters are array elements to insert into the array.
Use splice to delete an element in the array
sources.splice(3, 1);
trace(sources);
metacrawler,altavista,atomz,about

The 3 specifies that splicing will begin at the third element of the array; the 1 specifies that one element is to be deleted.
Use unshift to add elements to the beginning of the array
sources.unshift("dogpile");
trace(sources);
dogpile,metacrawler,altavista,atomz,about
sort the array alphabetically
sources.sort();
trace(sources);
about,altavista,atomz,dogpile,metacrawler

No comments:

Post a Comment