3 ms·
Here, let me make this easier for you > var hash = [] undefined > hash [] > hash['a'] undefined > hash['a'] = 33 33 > hash [ a: 33 ] > ha
by anonymous 14y ago
Here, let me make this easier for you
> var hash = []
undefined
> hash
[]
> hash['a']
undefined
> hash['a'] = 33
33
> hash
[ a: 33 ]
> hash[3] = 3
3
> hash
[ , , , 3, a: 33 ]
> hash[2]
undefined
> hash[hash]
undefined
> hash[hash] = hash
[ ,
,
,
3,
a: 33,
',,,3': [Circular] ]
> hash[0] = 'zero'
'zero'
> hash['0']
'zero'
JavaScript already has a perfectly well functioning associative array that can store whatever keys you like with the only gotcha being that strings containing only numbers act like numbers, when used as keys.
- lnanek2 14y agoI'm not a JS programmer, but isn't that just an array? Which extends Object. Which has all the failings that the article mentions? What happens when you try to insert hasOwnProperty? Do you lose access to the superclass hasOwnProperty like the {} object literal's drawback the article mentions? I suspect you do.
- Stratoscope 14y agoThat 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.