Thursday, March 10, 2011

Associative array

There no such thing like associative array in ActionScript. It would be too easy. In the other hand every object in AS3 is an associative collection of values. Here is example of how it works:

var assocArray:Object = new Object();

And that is all for creating. to set value we call setter

assocArray.price = 10000;

or more like aray

assocArray['price'] = 10000;

Reading looks similar:

assocArray.price

or

assocArray['price']

More complicated situation is with displaying full array. Trying to trace instance will cause something like this:

[object Object]

Also checking the size or length by variable of method doeas not help because returns zero. The easiest option is to create a for-each loop that displays all variables:

for (var item in assocArray)
{
    trace(item,' : ',assocArray[item]);
}

For counting elements the fastest solution is creating a loop that increments value for each item. But it's not good solution for big structures. In this situation good solution will be own class that controls records with push() and pop() methods.

No comments:

Post a Comment