【问题标题】:Iterate over jQuery JSON object in Chrome its changing the order在 Chrome 中迭代 jQuery JSON 对象以更改顺序
【发布时间】:2014-06-13 14:34:14
【问题描述】:

jquery + rails 4

json_data 实例中,我有一些带有键和值的数据,键是整数 id,值是包含数据的对象。但是,当我尝试使用 jQuery $.each 函数迭代这些数据时,结果返回按键排序。如何按原始顺序迭代我的对象集合?

$.each(json_data, function(key, value){
 console.log(key);
      });

key = 6181 30654 39148 30743 30510 42998 5788 30401 ...//Mozilla 工作正常(右)

key = 5788 6011 6181 30401 30510 30639 30654 30698 30743 ...// Chrome 无法正常工作(错误)

【问题讨论】:

标签: javascript jquery json google-chrome


【解决方案1】:

关于对象中的“顺序”:

JavaScript 对象是一个哈希表,并针对键值对的恒定时间查找进行了优化。

数组是一种数据结构,其中元素被分配给一个离散的索引值。当您遍历数组的元素时,您将返回一个与数组中项目的顺序相匹配的可预测模式。

然而,在一个对象中,没有索引值,因此没有恒定的可预测方式来按顺序迭代它。该对象仅存储针对常量时间查找优化的键:值对。

编辑:我将演示这两种迭代方法只是为了说明,但我想提前警告您,它们不会改变您不会以一致的顺序返回键的事实。

var json_data = {6181:true, 30654:true, 39148:true, 30743:true, 30510:true, 42998:true, 5788:true, 30401:true};
for(item in json_data){
  console.log(item);
} // *might* return a different order based on browser or JavaScript implementation

再次澄清:对象与特定的“订单”无关。它们经过优化以提供“恒定时间”查找。不管对象的大小,如果你查询一个键,关联的值会在恒定时间内返回给你。

如果您需要强制执行特定顺序,则需要使用数组。

例子:

var json_data = [6181, 30654, 39148, 30743, 30510, 42998, 5788, 30401];

for(var i = 0; i < json_data.length; i++){
  console.log(json_data[i]);
}
// always returns the values in the same order they are in the json_data array.
// changing the order in the array will change the order they are output and
// and that order will be the same regardless of which browser or version of JavaScript you
// are using.

【讨论】:

  • 使用for-with-分号循环遍历数组。并使用 for-in 循环遍历对象的键值。
  • var jsonData = {}; var newKey = 0; $.each(json_data, function(key, value){ newKey++; jsonData[newKey] = this; });不工作
  • 您好,如果您发现任何一个有用的答案,请选择一个作为官方答案。在这个网站上建立声誉有很大帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 2014-02-23
  • 1970-01-01
相关资源
最近更新 更多