I may be doing something really stupid, but I don’t get why the below code doesn’t work…
Here, I create a generic Object called spellbook:
// A list of all the player's spells
public var spellBook:Object = {};
Here, I add a key-value pair to the spellbook:
spellBook["bubble"] = new BubbleSpell(spellBook);
And here I try to output the contents of the spellbook:
trace("Spells initialised. Available spells are:");
for each (var _spell:String in spellBook)
{
trace(" ", _spell, " : ", spellBook[_spell]);
}
But this is the output I get:
Spells initialised. Available spells are:
[object BubbleSpell] : undefined
What I don’t get is why it’s not outputting:
Spells initialised. Available spells are:
bubble : [object BubbleSpell]
??
It’s as if I’m iterating over the values in spellbook, rather than the keys… is that what’s happening? All the docs I’ve seen so far seem to indicate that this is the correct way to iterate over a dictionary (which a generic object kind of is…) Do I need to call a method to get keys instead of values for generic objects?
So confused!
for eachis used to iterate over values, you want to use aforloop which iterates over keys, eg:Note that when iterating over the keys in a
Dictionaryyou should leave thekeyvalue untyped (*) as a Dictionary’s keys can be of any type (whereas anObject‘s keys can only be of typeString).A common trick would be to create a utility function which extracts an Object’s keys to an
Arrayfor easier iteration:You can then make use of this helper function: