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?