Manipulating Data with ActionScript in Flex Applications - Arrays (Page 3 of 5 )
Arrays are sets of data organized by integer indices or keys. ActionScript defines an Array type. New arrays are defined using an Array constructor as part of a new statement (which we’ll talk about in the next section, “Objects”), or using literal notation. The literal notation uses square brackets to create an array. The following creates a new empty array and assigns it to a variable:
var books:Array = ;
You can also populate an array by adding a comma-delimited list of values between the square brackets:
var books:Array = ["Programming Flex 2", "ActionScript 3.0 Cookbook"];
You can access specific elements of the array using array access notation. The following example retrieves the first element from the array (ActionScript arrays are 0-indexed) and displays it in the console (again, if you are debugging the application):
You can also assign values to elements using array access notation, as follows:
book = "Web Services Essentials";
Arrays are objects in ActionScript, and they have methods and properties like most objects. It’s beyond the scope of this book to delve into theArrayAPI in depth. However, of theArrayAPI, thelengthproperty andpush()method are the most commonly used. Thelengthproperty returns the number of elements in the array, and it is commonly used with aforstatement to loop through all the elements of an array. Thepush()method allows you to append elements to an array.
ActionScript arrays are not strongly typed. That means you can store any sort of data in an array, even mixed types. Theoretically, you could store numbers, strings, dates, and even other arrays in an array.
ActionScript does not have any formal hashmaps or similar types. ActionScript does have anObjecttype, which is the most basic of all object types. Unlike the majority of ActionScript classes theObjectclass is dynamic, which means you can add arbitrary properties toObject instances. Although it is generally better to write data model classes than to store data inObject instances using arbitrary properties, there are cases when it is useful to use anObject instance as a hashmap/associative array. The following example creates anObjectinstance and assigns several keys and values:
var authorsByBook:Object = new Object(); authorsByBook["Programming Flex 2"] = "Chafic Kazoun,Joey Lott"; authorsByBook["ActionScript 3.0 Cookbook"] = "Joey Lott,Keith Peters,Darron Schall";