Using associative arrays and for loops together

Hi All,
Can anyone help me with a query I have regarding associative arrays. Basically, I’m trying to use the current index of a for loop, which is looping through xml attributes, as the key for an associative array.


1    var attributes:Array = new Array();
2    for (attr in this.childNodes*.childNodes[j].attributes) {
3     //trace('		'+attr+' '+this.childNodes*.childNodes[j].attributes[attr]);
4     attributes[attr] = this.childNodes*.childNodes[j].attributes[attr]; 
5     trace( attr + " - " + atrributes[attr] )
6    }

So on line 4 of that code I want the key to be the current xml attribute name. Anyone know how I can do this?

Cheers,
Daf

Change line one to make attributes an object

 var attributes:Object = new Object();

If attr is in fact a string, this is all you should need to do.

take care.

_Michale

Yup. The Array type can only have numerical entries for keys. However, the Object type works essentially the same way as the array but can use any value for the key. =]

The reasoning is that the Object class is dynamic, meaning variables and methods can be added to any objects of that class, and the VM will handle memory allocation and such.

So essentially there is no difference, other than clarity between…


myObj["myVar"] = 5;

// and

myObj.myVar = 5;

The nice thing about subscript notation is the fact that you can use variables to create the variables name :), if that makes sense :stuck_out_tongue:

_Michael

Cheers Guys!
Worked perfectly
:thumb2:

no worries :slight_smile: GJ

Array is dynamic as well, otherwise you’d have to declare an infinite number of properties in the class.

Your real problem is that you spelt attributes wrong in the trace function - but Michael is right, you shouldn’t really use Arrays to store properties other than numerical ones.

:slight_smile:

Yes, TheCanadian is right. I wasn’t trying to imply that Array was not dynamic, I was explaining why you use an Object. An array here just didn’t make sense. Take Care.

_Michael

Damn typos! they’re the bane of my existance. One of these days I’ll learn to touch type, that’ll show 'em!