Enumerations are custom data types that programmers create to encapsulate a small set of values. For example, a programmer may want a variable to hold a specific day of the week. The programmer could simply use a string or an integer value to represent each day, but both of these options have disadvantages. The use of integers makes the code hard to read and maintain, but facilitates looping through the days of the week. The use of strings makes looping difficult, but makes the code more readable. Enumerations provide an elegant solution that stores both a string and an integer for each day of the week. This allows looping and makes the code easy to read.
ActionScript 3.0 does not support a specific enumeration facility, as does C++ with its enum keyword and Java with its Enumeration interface. You can achieve similar functionality in ActionScript, however, by using associative arrays. For example, the following code creates an associative array that contains each day of the week.
var Days:Object = {MON:0, TUE:1, WED:2, THU:3, FRI:4, SAT:5, SUN:6};
After creating a Days object, you can use its keys to assign values to variables:
var today:uint = Days.FRI;
You can also loop through the days of the week with a for...in loop:
for (var d:String in Days) {
if (today == Days[d]) {
trace ("Today is " + d)
}
}
// Output: Today is FRI
The advantage of using a for..in loop instead of a for loop is that a for...in loop gives you access to both the enumeration key and its value. A for loop would only give you access to the integer value of each key and value pair.