Initializing Arrays


So far we've been populating our arrays by accessing the individual indexes and using the assignment operator, or by multiple calls to the push method. Both these ways are valid, but they are not the only way. You can set up your arrays using the constructor for the method. (Constructors are discussed in Chapter 6.) Consider the following example:

 myArray = new Array("apple"," banana"," cabbage"); trace(myArray.toString()); 

In this example, the array gets three strings as its initial elements. These elements are given as arguments to the constructor for the Array object. For short arrays, this style of initialization can save time and screen space.

Another possible shortcut is as follows :

 myArray = new Array(); myArray = ["apple"," banana"," cabbage"]; trace(myArray.toString()); 

This script isn't as elegant as the first one, but it's still worth mentioning. As you can see, the array is first created and then populated with the assignment to ["apple"," banana",cabbage"] .

Note  

By using the type of initialization used in the previous example, you can get away with omitting the line that creates the array. When Flash sees the myArray = [] part, it automatically creates a new array, so the preceding script could have simply been the following:

  myArray = ["apple"," banana"," cab-   bage"];   trace(myArray.toString());  

This is called an implicit instantiation of the Array object. The reason I don't like this style is because it does not explicitly state that myArray is an array. It relies on the reader of the code to know that the implicit instantiation creates an Array object.




Macromedia Flash MX 2004 Game Programming
Macromedia Flash MX 2004 Game Programming (Premier Press Game Development)
ISBN: 1592000363
EAN: 2147483647
Year: 2004
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net