admin 管理员组文章数量: 1086019
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.
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.
Share Improve this question edited May 4, 2016 at 8:02 Mohammad Usman 39.4k20 gold badges98 silver badges99 bronze badges asked Sep 27, 2008 at 17:59 Felix FFelix F2 Answers
Reset to default 9Technically, "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:
<script type="text/javascript">
//define and initialize your object/hastable
var obj = {};
obj[20] = 'C';
obj[10] = 'B';
obj[-10] = 'A';
// get the indexes and sort them
var indexes = [];
for(var i in obj){
indexes.push(i);
}
indexes.sort(function(a,b){
return a-b;
});
// write the values to the page in index order (increasing)
for(var i=0,l=indexes.length; i<l; i++){
document.write(obj[indexes[i]] + ' ');
}
// Should print out as "A B C" to the page
</script>
You're bumping into the boundary between Array
s and Object
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:
var arr = new Array();
arr[0] = 'A';
arr[1] = 'B';
arr[-1] = 'C';
arr.length
The result is 2 - there are only two elements in the array, at indices 0 and 1.
本文标签: javascriptTraversing negative Array indeces in JScriptStack Overflow
版权声明:本文标题:javascript - Traversing negative Array indeces in JScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744001996a2516616.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论