I’ve set up a jsFiddle example of my problem: Example
Given this html:
<select id="drop1" data-jsdrop-data="countries"></select>
<select id="drop2" data-jsdrop-data="countries2"></select>
And the following javascript:
var countries = {"1" : "Albania", "5" : "Australia","2": "United Arab Emerates"};
var countries2 = {"AL" : "Albania", "AU" : "Australia", "AE" : "United Arab Emerates"};
function loadJSOptions(selector, list) {
$.each(list, function (key, value) {
$(selector).append($("<option></option>").val(key).html(value));
}
});
$(document).ready(function() {
$('select[data-jsdrop-data]').each(function() {
var selector = $(this);
var listname = selector.attr("data-jsdrop-data");
var listvalue = null;
eval("listvalue = " + listname + ";");
loadJSOptions(selector, listvalue);
});
});
Can anyone explain to me why the list with the Alpha key gets listed based on the order entered while the list with the numeric key gets sorted based on the key? If you look at the jsFiddle results, you’ll see that drop1 shows Albania, United Arab Emerates, Australia while drop2 shows Albania, Australia, United Arab Emerates.
Thanks for your help.
Object properties are not ordered, if you enumerate them the order is implementation-defined. They often are stored in the order the object literals were parsed, but you can’t rely on that. For example, numeric keys (as in
countries1) seem to be sorted in your browser.If you want a definite order, use an array (an object with numeric keys) and iterate them:
A for-loop is much faster and more intuitive than
$.each. Don’t use that when you don’t know exactly what it does and when you need it.