There is some strangeness while I create in JavaScript Select element:
var items = {"3":"Three","1":"One","2":"Two"};
var elem = document.createElement("select");
for ( var key in items) {
var ov = document.createElement("option");
ov.value = key;
ov.appendChild(document.createTextNode(items[key]))
elem.appendChild(ov);
}
document.getElementById('someDiv').appendChild(elem);
FF create Select element with initial elements order (Three, One, Two).
Chrome sorts elements by key and output in next way (One, Two, Three).
Why this happen? And how prevent sorting in Chrome?
The
for … instatement iterates over an object in an unpredictable order. As MDC says:You’d better use an array of objects and use an ordinary
forloop to keep the specified order, like:Just a side note: when iterating over object using
for … in, you really should usehasOwnPropertyto check whether it is an inherited property or not, otherwise you might include inherited properties in yourselectbox.