Associative array is out of order

Associative array order is similar

A00 = > value1
A01 = > value2
B01 = > value3
B02 = > value4

But after the order of the array does not work for the loop

for (var key in obj3) {
    $("#code_list1").append(obj3[key]);
}

The console output is the same as in the image. enter image description here

+4
source share
2 answers

Javascript objects like this do not maintain order; this is the expected behavior.

You can use some simple methods to extract a list of keys from this and sort.

Then use the sorted list to do what you need.

var keys = Object.keys(obj3).sort();

for (var i = 0; i < keys.length; i++) {
    console.log(keys[i]);
    $("#code_list1").append(obj3[keys[i]]);
}

http://jsfiddle.net/rmvoz6av/3/

As Robert said, I changed this to Object.keys (), although some older IE browsers will not support this.

+4
source

. . , , - , , , , - .

" " . , runtume , , . , : . , - , .

JavaScript, , Object.keys , . , IE9, , .

/**
 * Determine the relative positions of two keys.
 *
 * I don't know exactly how you're determining your ordering here,
 * but unless it basic alphabetical order, you'll need a function
 * like this for sort() to work properly.
 *
 * @param {*} a - One of the keys to compare.
 * @param {*} b - The other key to compare.
 *
 * @return {Number} The relative positions of the two keys.
 *     - If a should come before b, return a number less than 0.
 *     - If b should come before a, return a number greater than 0.
 *     - If their ordering isn't important, return 0.
 */
function compareKeys(a, b) {
    // This implementation just does what JavaScript does normally
    // for sorting, but it should illustrate how to implement your own.
    if (a < b) { return -1; }
    if (a > b) { return 1; }
    return 0;
}

// The code to iterate over the array.
var keys = Object.keys(obj3).sort(compareKeys),
    key,
    i;
for (i = 0; i < keys.length; i += 1) {
    key = keys[i];
    $("#code_list1").append(obj3[key]);
}
+1

All Articles