Javascript Objects dont act like pure hash tables

This behavior is cross browser (IE, Firefox, Opera). When storing a key/value pair, the actual key is not used; instead the value from key.toString() is used as the key. This results in being able to use different objects to lookup the same value. In the below example the variables "key" and "key3" can both be used to lookup the variable "element1"

If the toString() method is changed, like key2 in the below example, then a different value will be looked up.

var hash = new Object;
var key = new Object;
var key2 = new Object;
key2.toString = function(){ return "Something other than object" };
var key3 = new Object;

var element1 = "I am the first element in an array";
var element2 = "Some other element";

hash[key] = element1;
hash[key2] = element2;

alert("hash[key]: " + hash[key] );
alert("hash[key2]: " + hash[key2] );
alert("hash[key3]: "+ hash[key3] );

Click Here to Run

See here for a bug that can affect IE becuase of this

Hosted by www.Geocities.ws

1