Reputation: 33
I have an array in ActionScript 3 that is formatted as follows:
var _arrayList = new Array;
_arrayList["item1"] = true;
_arrayList["item2"] = 56;
_arrayList["item3"] = "john doe";
_arrayList["item4"] = -56.8;
and I'm attempting to pull the "_arrayList.Length" but it comes back 0... why?
Upvotes: 0
Views: 38
Reputation: 7510
Because the way you do it makes the array "associative". In Action Script, every class is a basic Object, with dynamic properties. And array does both - containing indexed elements, and having a dynamic properties.
Here's an example of a regular array:
var array:Array = new Array();
array.push(value); // equal to array[0] = value;
array.push(56); // equal to array[1] = value;
array[20] = 'test'; // will put 20th element to be 'test'
If you use this approach, the length
of the array will not be 0
. And so you can use a for
loop:
var total:uint = array.length;
for (var i:uint = 0; i < total; i++) {
trace (array[i]);
}
But when the keys are not numeric, you are actually setting "properties" to the array and thus the length is 0
. Again, you can loop through them, but with for-in
:
for (var key:String in array) {
trace (array[key]);
}
Here the keys won't be 0, 1, 2, 3
and so on, but instead will be item1, item2, item3
. (keep in mind that the order is not preserved!)
So the basic conclusion is that if you use non-numeric keys, then use an Object instead. Array is for numeric indexed collections.
Upvotes: 1