Organizing data in objects
109
This code, which is one way to create a simple object, creates a new object instance and
defines a few properties within the object.
3.
Now enter the following ActionScript after the code you entered in step 2.
// The second way
var secondObj:Object = {firstVar:"hello world", secondVar:28,
thirdVar:new Date(1980, 0, 1)};
This is another way of creating an object. Both objects are equivalent. This code above
creates a new object and initializes some properties using the object shorthand notation.
4.
To loop over each of the previous objects and display the contents of objects, add the
following ActionScript on Frame 1 of the Timeline (after the code you’ve already entered):
var i:String;
for (i in firstObj) {
trace(i + ": " + firstObj[i]);
}
5.
Select Control > Test Movie, and the following text appears in the Output panel:
firstVar: hello world
secondVar: 28
thirdVar: Tue Jan 1 00:00:00 GMT-0800 1980
You can also use arrays to create objects. Instead of having a series of variables such as
firstname1
,
firstname2
, and
firstname3
to represent a collection of variables, you can
make an array of objects to represent the same data. This technique is demonstrated next.
To use an array to create an object:
1.
Create a new Flash document, and save it as
arrayObject.fla
.
2.
Select Frame 1 of the Timeline, and type the following ActionScript into the Actions panel:
var usersArr:Array = new Array();
usersArr.push({firstname:"George"});
usersArr.push({firstname:"John"});
usersArr.push({firstname:"Thomas"});
The benefit of organizing variables into arrays and objects is that it becomes much easier
to loop over the variables and see the values, as shown in the following step.
3.
Type the following code after the ActionScript you added in step 2.
var i:Number;
for (i = 0; i < usersArr.length; i++) {
trace(usersArr[i].firstname); // George, John, Thomas
}
4.
Select Control > Test Movie, and the following text appears in the Output panel:
George
John
Thomas
Summary of Contents for FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH
Page 1: ...Learning ActionScript 2 0 in Flash...
Page 8: ...8 Contents...
Page 18: ...18 Introduction...
Page 30: ...30 What s New in Flash 8 ActionScript...
Page 66: ...66 Writing and Editing ActionScript 2 0...
Page 328: ...328 Interfaces...
Page 350: ...350 Handling Events...
Page 590: ...590 Creating Interaction with ActionScript...
Page 710: ...710 Understanding Security...
Page 730: ...730 Debugging Applications...
Page 780: ...780 Deprecated Flash 4 operators...
Page 830: ...830 Index...