在 JScript 中遍历负数数组
我在 Jscript 中有一个稀疏数组,负索引和正索引均出现非空元素。 当我尝试使用 for in 循环时,它不会从最低(负)索引到最高正索引遍历数组。 相反,它按照我添加元素的顺序返回数组。 枚举也不起作用。 有什么方法可以让我做到这一点吗?
示例
arrName = new Array();
arrName[-10] = "A";
arrName[20] = "B";
arrName[10] = "C";
循环时,它应该给我 A 然后 C 给 B。
I have a sparse array in Jscript, with non-null elements occuring at both negative and positive indices. When I try to use a for in loop, it doesn't traverse the array from the lowest (negative) index to the highest positive index. Instead it returns the array in the order that I added the elements. Enumeration doesn't work either. Is there any method that will allow me to do that?
Example
arrName = new Array();
arrName[-10] = "A";
arrName[20] = "B";
arrName[10] = "C";
When looping through, it should give me A then C the B.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从技术上讲,“A”根本不在数组中,因为不能有负索引。 它只是 arrName 对象的成员。 如果你检查 arrName.length 你会发现它是 21 (0,1,2,...,20) 为什么不使用普通对象来代替(作为哈希表)。 像这样的东西应该有效:
Technically, "A" isn't in the Array at all since you can't have a negative index. It is just a member of the arrName object. If you check the arrName.length you will see that it is 21 (0,1,2,...,20) Why don't you use a plain object instead (as a hashtable). Something like this should work:
您遇到了 Javascript 中的
Array
和Object
之间的边界。 数组元素通过序数访问,序数是 0 到 4294967294 之间的整数(最大无符号 32 位整数 - 1)(包括端值)。 对象属性通过名称访问。 由于 -10 不是有效的序数,因此它被解释为名称。 下面是一个更简单的示例:结果为 2 - 数组中只有两个元素,索引分别为 0 和 1。
You're bumping into the boundary between
Array
s andObject
s in Javascript. Array elements are accessed by ordinal, an integer between 0 and 4294967294 (maximum unsigned 32-bit integer - 1), inclusive. Object properties are accessed by name. Since -10 isn't a valid ordinal number, it is interpreted as a name. Here's a simpler example:The result is 2 - there are only two elements in the array, at indices 0 and 1.