Arrays - stumped

ahmed = []
ahmed["a"] = "sdf"
ahmed["b"] = "asd"
trace(ahmed.length) // outputs 0

ahmed = []
ahmed[0] = "sdf"
ahmed[1] = "asd"
trace(ahmed.length) // outputs 2

I got two questions:

a) Why does the first piece trace 0 instead of 2?
b) How would i loop through an array where the indexes are literal (not numbers)

any help would be appreciated :slight_smile:

arrays (lengths) are number based. :-\

Ahmed, in the first case you are using associative array.

ahmed = []
ahmed["a"] = "sdf"
ahmed["b"] = "asd"
trace(ahmed["a"]) // outputs sdf

I think you cannot retrieve its length since associative array isnt based on index numbers.

I think he’s trying to do enumeration.

[AS]
ahmed = [{a:“sdf”,c:“whatever”},{b:“afd”}]
trace(ahmed[0].a) // outputs sdf
trace(ahmed[0].c) // outputs whatever
trace(ahmed[1].b) // outputs afd
trace(ahmed.length) // outputs 2

ahmed = []
ahmed[“a”] = "sdf"
ahmed[“b”] = "asd"
trace(ahmed[“a”]) // outputs sdf

ahmed = []
ahmed[0] = "sdf"
ahmed[1] = "asd"
trace(ahmed.length) // outputs 2
[/AS]
I didn’t manage to get the length of the array using “a” and “b”, since arrays are number based, but if you want to use letters at all costs, you could use the above using objects. This is basically similar to nested arrays, only I’m using objects.

1)What sen said :stuck_out_tongue:

  1. What sen is about to say :P:P

if you want, you could always make your own method for checking that

Object.prototype.addProperty("propertyNum",function(){
		var L = 0;
		for (var i in this) L += this.hasOwnProperty(i);
		return L;
	},null);

ahmed = []
ahmed["a"] = "sdf";
ahmed["b"] = "asd";
ahmed[0] = "sdf";
ahmed[1] = "asd";
trace(ahmed.length) // outputs 2
trace(ahmed.propertyNum) // outputs 4

thanks for the proto sen :slight_smile:

I just realized that I can for…in-loop through the associative array, that i think solves it :slight_smile: