In Javascript, I have an array of objects, users, such that users[1].name would give me the name of that user.
I want to use the ID of that user as the index instead of the ever increasing counter.
For example, I can initiate the first user as users[45].
However, I found that once I do users[45], javascript would turn it into a numeric array, such that when I do users.length, I get 46.
Is there anyway to force it to treat the number as string in this case. (” ” doesn’t work)?
You cannot use arrays for this sort of function in JavaScript — for more information, see “Javascript Does Not Support Associative Arrays.”
Make sure you initialize the
usersvariable as anObjectinstead. In this object you can store the arbitrary, non-sequential keys.To get the number of users in the object, here’s a function stolen from this SO answer: