I have a sparse array whose contents aren't guaranteed to be inserted in index order but need to be iterated through in index order. To iterate through a sparse array I understand that you need to use a for..in statement.
However, according to this article:
There is no guarantee that for...in will return the indexes in any particular order
But stackoverflow questions like this suggest that whilst object property orders are not guaranteed, array orders are:
properties order in objects are not guaranted in JavaScript, you need to use an Array.
I tested 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>");
}
All appear to honor the index order so can I trust this always to be the case? Otherwise, how do I best get them in index order?
for..in
order is guaranteed with arrays. (I'm not saying that it isn't, but that line isn't really saying that it is). Plus, there are very good reasons to avoid usingfor..in
with arrays, even if the ordering works out ok. – Luaneidx
defined in your functionaddItem
? – Deputize