views:

127

answers:

5

Hi when I have an array in actionscript

var arr : Array = new Array();
arr["fsad"] = 1;
trace(arr.length);

and now put an entry to it with an associative string and afterwards count the length I get a length of 0 but why? How can I iterate it now?

Thanks in advance

Sebastian

+2  A: 

What you want to accomplish is called a Dictionary i guess :)

Andy Jacobs
+1  A: 

Well, to quote the reference:

Do not use the Array class to create associative arrays (also called hashes), which are data structures that contain named elements instead of numbered elements. To create associative arrays, use the Object class. Although ActionScript permits you to create associative arrays using the Array class, you cannot use any of the Array class methods or properties with associative arrays.

I'm not sure why AS3 still allows Arrays to be used associatively - perhaps they were worried about AS2 migration - but it's best avoided. So far as I know, built-in Array fixtures like length and pop() will simply ignore anything added with a a key that isn't an integer, but they might also behave unpredictably.

fenomas
+1  A: 

There is a post describing the same problem as you mentioned

http://stackoverflow.com/questions/284947/how-do-i-find-the-length-of-an-associative-array-in-actionscript-3-0

I hope that it will help

funkydokta
A: 

In JavaScript (which is a brother of ActionScript) using spidermonkey:

var obj = new Object(); // {}
obj["foo"] = 1;
print(obj.__count__); => 1 // non-standard Gecko

var arr = new Array(); // []
arr.push(1);
print(arr.length); => 1

Use Array for arrays and Object for dictionaries. It's not like PHP where everything is done using the same type.

greut
A: 

you can create you own associative arrays using Proxy ... this will come at a high performance cost, but you can implement array access overriding getProperty and setProperty, and for each in and for in overriding nextNameIndex as well as nextValue and nextName respectively ... you can also implement Array's forEach, filter, map, any, every etc. methods, so it looks like a real Array from outside ... but you should only do that, in situations, where it is not performace critical or unevitable ...

back2dos