2 ms·
That has a couple of problems. Try this: > var hash = []; undefined > hash [] > hash['length'] 0 > // Hey! That should have been undefined, not 0
by Stratoscope 14y ago
That has a couple of problems. Try this:
> var hash = [];
undefined
> hash
[]
> hash['length']
0
> // Hey! That should have been undefined, not 0!
> hash['length'] = 'test'
RangeError: Invalid array length
> // And I can't set it either!
Also, the part where you're doing hash[hash] doesn't do at all what you think. When you write this code:
hash[hash] = whatever;
What you're really doing is:
hash[ hash.toString() ] = whatever;
And with hash being an array, hash.toString() is highly browser dependent. In Chrome, if you don't have any numeric array keys, then hash.toString() is "" regardless of your non-numeric keys (at least in the version I'm testing). So you may well be really doing this in Chrome:
hash[""] = whatever; // Oops
If you do want to use a native JavaScript type as a hash, the one to use is Object, not Array. Simply change the first line of your test to:
var hash = {};
and go from there.
This still doesn't solve the name collisions, but is plenty useful anyway.
If you do want a more fool-proof hash that lets you use any string as a key without fear, I'm pretty sure you need to write some code like the Hash class I posted. You still couldn't do the hash[hash] - or hash.get(hash) - because of the dependence on .toString(), but any string key would work. You could even get fancy and give the Hash class some kind of useful .toString() method so you could use hash[hash] - having your own code here opens up those kinds of possibilities.