Don't do this with arrays. All objects in ECMAScript can be modified in this way. Using Array is a bad choice because ECMAScript arrays are meant to be unique, and it's entirely reasonable for a script to extend Array, breaking the only method of enumeration available for such hashes, the for..in loop. Instead, either use a plain Object:
Code:
var myhash = {};
myhash['fish'] = 5;
(print || alert)(myhash['fish']); // 5
(print || alert)(myhash.fish); // 5
This has the added advantage that you can use the standard object literal:
Code:
var myhash = {
'fish' : 5
};
(print || alert)(myhash['fish']); // 5
(print || alert)(myhash.fish); // 5
You can also create your own Hash constructor, or use one of the ones available on the Internet (have a look for Rick Measham's version, in particular: I can't seem to find it, but I remember it being a fairly well-implemented one). This option allows you to create new methods for your hashes without the fear of breaking existing code (always try to avoid extending Object).
Bookmarks