PDA

View Full Version : Traversing an Associative Array


tiggyboo
02-11-2003, 10:11 PM
How do I go about traversing an associative array via a loop without knowing the names of all the elements?

I.e.

var myarray = new Array();

myarray["first_name"] = "Joe";
myarray["last_name"] = "Smith";

How to a traverse this array without having to specify "first_name" or "last_name", i.e., to dump the contents of the array?

Thanks in advance,
Tiggy

beetle
02-11-2003, 10:14 PM
Two ways
function dumpArray( arr )
{
for ( var i = 0; ( val = arr[i] ); i++ )
{
alert( val );
}
}

// or

function dumpArray( arr )
{
for ( var key in arr )
{
alert( key + ": " + arr[key]);
}
}The 2nd method obviously gives you access to the key names, where the 1st doesn't. There is a caveat to the 2nd method, however: any custom methods you define for arrays will be picked up by this loop.

whammy
02-12-2003, 01:31 AM
ahh, this is just like C#. I love it.