关联数组不按顺序排列

关联数组的顺序是这样的

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

但是对于数组的循环顺序不起作用

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

控制台输出与图像一样 在此处输入图像描述

像这样的Javascript对象不支持顺序,这是预期的行为。

您可以使用一些简单的方法从中提取密钥列表并对其进行排序。

然后使用排序列表来执行您需要的操作。

 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/

正如Robert建议我将其更改为Object.keys(),尽管一些较旧的IE浏览器不支持此function。

在关联数组中,顺序不重要 。 这是结构定义的一部分。 当然,在逻辑上,必须某种排序,以便计算机可以跟踪哪些条目在哪里,但不能保证排序是基于任何特定的。

这使得简单地依赖关联数组中元素的“自然顺序”变得很危险。 如果你的runtume碰巧按照你想要的顺序放置东西,它可能会巧合。 但巧合的function有一个令人讨厌的习惯,当你最不期望它时会破坏:运行时间改变。 要迭代关联数组,使用基于键的某种排序,最好明确地对键进行排序

在JavaScript中,如果您使用Object作为关联数组,那么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's 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]); }