Array negative bypass in JScript

I have a sparse array in Jscript, with non-zero elements having both negative and positive indexes. When I try to use a for for loop, it does not intersect the array from the lowest (negative) index to the highest positive index. Instead, it returns the array in the order in which I added the elements. Enumeration does not work either. Is there a way that allows me to do this?

Example

arrName = new Array();
arrName[-10] = "A";
arrName[20] = "B";
arrName[10] = "C";

When passing through it, he should give me A, and then C B.

+3
source share
2 answers

"A" , . arrName. arrName.length, , 21 (0,1,2,..., 20). ( -). - :

<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>
+9

Array Object Javascript. , 0 4294967294 ( 32- - 1) . . -10 , . :

var arr = new Array();
arr[0] = 'A';
arr[1] = 'B';
arr[-1] = 'C';
arr.length

2 - : 0 1.

+4
source

Source: https://habr.com/ru/post/1697607/


All Articles