在Chrome中迭代jQuery JSON对象,它改变了顺序

Iterate over jQuery JSON object in Chrome its changing the order

本文关键字:改变 顺序 对象 JSON Chrome 迭代 jQuery      更新时间:2023-09-26

Jquery + rails 4

json_data实例中,我有一些带有键和值的数据,键是一个整数id,值是包含数据的对象。然而,当我尝试迭代这些数据与jQuery $。每个函数,返回的结果都是按键排序的。我如何能迭代我的对象集合在他们的原始顺序?

$.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不能正常工作(错误)

关于对象中的"order":

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.