Click to See Complete Forum and Search --> : how do I get the keys of my array?


jessevitrone
11-30-2002, 10:13 AM
I'm using the Array class more like a Hashtable (since I couldn't find one for Javascript).

var array = new Array();
array['name'] = "joe";
array['face'] = "ugly";

Now, I my code, I need to generate a string that looks like this:

name=joe&face=ugly

but I don't know how to loop through and get the keys (maybe index is a better word) from my array.

"name" and "face" could be any values, and I just want to loop though all the keys, and look up their values.

How do I do this with JavaScript? I can't find a way.

Maybe I'd be better off using something besides an Array? I don't really see any other data structures for storing things like this though.

Any suggestions will be greatly apprieciated.

Thanks.

gil davis
11-30-2002, 11:12 AM
First, do not use a reserved word for a variable.

var ary = new Array();
...
st = "";
for (var i in ary)
{if (st != "") st += "&";
st = st + i + "=" + ary[i]}
alert(st);

Charles
11-30-2002, 11:52 AM
In Perl we use hashes to make objects. In JavaScript we use objects to make hashes:

<script type="text/javascript">
<!--
myObject = {name:'joe', face:'ugly'};
for (key in myObject) {document.write(key, '<br>')}
// -->
</script>

jessevitrone
12-02-2002, 08:31 AM
Ah...I didn't know you could do something like this:


for (var i in ary)

That's exactly what I was looking for.

Thanks Gil and Charles for the quick, helpful response.

Jesse