0

PHP:

 $arr[0] = 'A';
 $arr['C'] = 'C';
 $arr[10] = 'B';

 echo json_encode($arr);

查询:

 $.each(result, function(i, item) {
    console.log(i + " => " + item);
 });

期望的输出:

   0 => A
   C => C
   10 => B

相反,我得到:

   0 => A
   10 => B
   C => C

如何防止它在不修改 PHP 代码或重组数组的情况下重新排序我的数组?

编辑:

当使用 firebug 在响应标头中调用 ajax 时,它的顺序似乎正确:

"0":"A","C":"C","10":"B"

但是,当我在 $.each 循环中执行 console.log 时,它会重新排序

4

1 回答 1

3

Your $arr is an object, not an array and the keys aren't indexed nor ordered.

You don't have guarantee in JavaScript about the iteration order on object properties, only the indexed keys (i.e. integer keys) of arrays.

To iterate over a plain object, $.each uses the standard for..in construct on which the MDN precises that

A for...in loop iterates over the properties of an object in an arbitrary order

If you want to keep arbitrary key-value ordered, you should store both in a proper array :

  var arr = [];
  arr.push({key:0, value:'A'});
  arr.push({key:'C', value:'C'});
  arr.push({key:10, value:'B'});
于 2013-04-22T18:48:28.337 回答