Hacker News new | ask | show | jobs
by Zef 5958 days ago
Alright. So now I want to iterate over all original keys, how do I do that (i.e. their original values, not the stringified version)?

Plus, a random object (that doesn't have a meaningful toString method) will probably result in something like "[object]" as a key, which would break when you use more objects like that as keys.

2 comments

Yeah agreed. The edit was intended to concede that your statement about only being able to use strings was technically correct and mine about using objects was misguided :)

One good use case for objects as keys in hashes is functions. When you use a function as a key it is reliably converted to its definition, cross-browser. Doesn't make your point any less valid though.

> So now I want to iterate over all original keys, how do I do that

for(var key in obj) { if(obj.hasOwnProperty(key)) val = obj[key]; }

Or did I misunderstand the question?

The key is now effectively '1,2,3' in the case [1,2,3] . You can iterate using that string and even pass in the array using bracket notation. But when you iterate using for..in the key will be a string not the original array, and you lose that data. The string is now indistinguishable from the subset of strings with comma delimkted data. May that is inconsequential in your app but for some apps it dampens the effectiveness of the construct.

Ain't JavaScript a riot? [I just found an excuse to use snowclone in an HN comment. Pats self on back]

Functions on the other hand work very well because the key is the function definition (call toString on a function). There is no reason for two functions to have the exact same definition in JavaScript.