views:

152

answers:

1

Hello,

When you do a "for... in" loop, it will iterate over a Dictionary for example. I was wondering how internally this is being tracked and how it could be accessed?

I think the Dictionary class stores a reference to the first item, but I would like to access it and check but I cannot figure out how. This is a bit advanced, does anyone please have an idea?

Thanks, Rudy

A: 

Hey Rudy.

ActionScript's Dictionary class isn't really an ordered collection. In other words, it doesn't really have a "first item." Of course, if you iterate through the items using a for or for each loop, one of the items has to be accessed first so you could do something like this:

var firstKey:*;
var firstValue:*;
for (firstKey in myDictionary)
{
   firstValue = myDictionary[firstKey];
   break;
}
// variables now hold the "first" key and value, or undefined if the dictionary is empty.

However, the Dictionary class has no contract about the order of the items, and even if the order were predictable (alphabetical keys, first assigned==first returned, etc), I would consider it an implementation detail that's subject to change between player versions. In addition, the class doesn't expose any internal map that you could access.

If you really care about controlling iteration order (or just want an idea of how it's handled in ActionScript), I would suggest checking out the Proxy class. By extending it and overriding a few methods, you can control the order in which items are iterated over, as well as some other cool stuff. (The methods related to iteration are nextName(), nextNameIndex(), and nextValue(), and there's an example in the official documentation.) This way, you can create your own Dictionary-like collection class that also indexes items.

Alternatively, you could look into third party Collection/Iterator packages, which may already have something like what you need.

matthew
Thanks Matthew, this is a very complete explanation. I am using the loop with the break statement like you suggest, but I am taking into account that the ordering is subject to change, and not well defined. I am going to follow your advice and create my own class. Thanks a lot!
Rudy
Happy to help! Thanks for accepting my answer.
matthew