How should iterate over a sparse array in index order?

I have a sparse array whose contents are not guaranteed to be inserted in index order, but it needs to be repeated in index order. To iterate through a sparse array, I understand that you need to use the for..in operator.

However, according to this article :

There is no guarantee that for ... in will return indexes in any particular order

But https://stackoverflow.com/a/4646262/2126321 , but the orders for the object are not guaranteed, massive orders:

the order of objects in objects is not guaranteed in JavaScript, you need to use an array.

I checked this in the latest versions of Chrome, Firefox and IE.

<ol id="items"></ol> 
 var list = []; function addItem(index) { list[index] = { idx : index }; } var insertOrder = [ 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 ]; for ( var i = 0; i < 15; i++ ) { addItem(insertOrder[i]); } for(var item in list) { $("#items").append("<li>" + list[item].idx + "</li>"); } 

Everyone seems to be indexed, so can I always trust this? Otherwise, how would I best get them in index order?

+5
source share
1 answer

MDN has the answer to your original question:

Note: for..in should not be used to iterate over an array where the sequence of indices is important.

Array indices are simply enumerated properties with integer names that are otherwise identical to the general properties of the object. There is no guarantee that for ... in it will return indexes in any particular order and return all enumerable properties, including those with non-integer names and inherited ones.

You don't need to use for..in to iterate over a sparse array, and you should definitely avoid this if you can.

You can simply use .forEach :

 list.forEach(function (el) { // add a second parameter if you need the indices $("#items").append($("<li>").text(el.idx)); }); 

forEach defined to iterate in index order and includes only the elements present in the array:

forEach executes the provided callback once for each element present in the array, in ascending order. It is not called for indexes that have been deleted or deleted. However, it is executed for elements present and has the value undefined.


If you target environments that do not support forEach , you can use the following or the padding provided on this MDN page:

 for (var i = 0; i < list.length; i += 1) { if (i in list) { $("#items").append($("<li>").text(list[i].idx)); } } 
+10
source

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


All Articles