[thelist] tips

Marcus Andersson marcus at bristav.se
Thu Aug 26 16:06:25 CDT 2004


Diane Soini wrote:
> <tip type="Javascript arrays">
> Most people understand javascript arrays as being indexed arrays. But 
> javascript arrays can also be hashtables, with each element having a key 
> that maps to a value. In an indexed array, the key is the number. In a 
> hashtable, the key is something else.
> 
> A hashtable is very handy when, for example, you want to find unique 
> names in a long list with duplicates. Iterate through the list and set 
> each array element to something like myarray['Jane'] = 'Jane'; 
> myarray['Mike'] = 'Mike'; As you iterate the list, duplicates will be 
> cancelled out and you'll be left with only the unique items.
> 
> To retrieve them you can use a for-loop like you usually see one, or you 
> can use a control structure like this:
> for(var i in myarray){
>     alert(i); //will tell you the key
>     alert(myarray[i]); //will tell you the value
> }
> </tip>

This isn't a property of the Array object/class per se. It is a property of the Object object (which Array 
inherits from, as does every other object/class in javascript). You can create an object like this:

var o = new Object();
o["prop1"] = "value1";
o["prop2"] = "value2";

Or the shorthand:
var o = { prop1 : "value1" , prop2 : "value2" }

And then you can loop over them exactly as you did in your example. There are two ways of accessing these 
properties. The normal property way (the dot notation) and with square brackets.

var val1 = o.prop1;
var val2 = o["prop2"];

The second way is very good when you need to do dynamic lookups.

You can even attach functions as properties of objects and invoke them as follows:

var o = new Object();
o["fun1"] = function() { alert("i'm a function"); }
o["fun1"](); // will invoke the function
// the following is the more "normal" way to invoke it
o.fun1();

Using the square bracket way is good when you need to invoke it dynamically and you don't know up front what 
function you need to invoke (another way is of course eval).

So, in short, you don't need to use Array to accomplish the hashtable effect. Plain old Object will suffice.

/Marcus


More information about the thelist mailing list