javascript 使用数字数组作为关联数组
在 Javascript 中,我有一个对象(用户)数组,这样 users[1].name 就会给我该用户的名称。
我想使用该用户的 ID 作为索引,而不是不断增加的计数器。 例如,我可以将第一个用户启动为 users[45]。
但是,我发现一旦我执行users[45],javascript就会将其转换为数字数组,这样当我执行users.length时,我得到46。
在这种情况下,有没有办法强制它将数字视为字符串。 (“”不起作用)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在 JavaScript 中使用数组来执行此类函数 — 有关详细信息,请参阅 "Javascript 不支持关联数组。”
确保将
users
变量初始化为对象
代替。在此对象中,您可以存储任意的、非顺序的键。要获取对象中的用户数量,这是从这个SO答案中窃取的函数:
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
users
variable as anObject
instead. 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:
汉斯在这里有正确的答案。在对象上使用键,而不是在数组上。我建议您阅读这两篇参考文献:
http://www.quirksmode.org/js/associative .html 和
http://blog.xkoder.com/2008/07/ 10/javascript-associative-arrays-demystified/
尝试从数组对象中创建关联数组是非标准的,可能会导致问题(例如 .length 将是 零)。请改用对象上的键。
Hans has the right answer here. Use keys on an object, not an array. I'd suggest you read these two references:
http://www.quirksmode.org/js/associative.html and
http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/
Trying to make an associative array out of an array object is non-standard and can cause problems (for example .length will be zero). Use keys on an object instead.