33 ms·
Arrays are not hashes
by skwaddar 17y ago
Arrays are not hashes
- tlrobinson 17y agoYeah I don't know why the author expected any reasonable behavior from using a string as an array index. However, the same behavior is true of plain Objects.
- s3graham 17y agoI used [] because I hoped it would correctly handle number indices. But, I originally used {}. The auto-stringification of the keys was my complaint.
- axod 17y agoAll keys are strings :/ What you're complaining about is similar to complaining that "hello " + 3 + " world" == "hello " + "3" + " world"
- invisible 17y agoWhen assigning a String with a numeric value I think JavaScript treats it as a numeric for an Array and a String for regular Objects. This doesn't really change the difference, just that an Array should hold numerical index values (vs an Object key, but they CAN hold regular keys since they are an Object). A bit confusing I guess...
- tolmasky 17y agoIt is reasonable to expect to be able to set arbitrary properties on an Array and have them behave differently than it's indexes, despite the fact that this is not how it works. The language even suggests this is possible by providing certain properties that are not enumerated (such as "length"). What's worse is that the true answer to why this behaves the way it does is that in JS arrays are (kind of) hashes.
- invisible 17y agoYes and no (as you said). Just expanding: Arrays are an instance of Object with a few specialized methods. Therefore, you can (but should not) assign keys with values to the array and it will apply correctly. However, then you lose a great deal of the advantage of it being an Array.