Is the order of elements in a JSON list preserved?

后端 未结 5 849
半阙折子戏
半阙折子戏 2020-11-22 12:20

I\'ve noticed the order of elements in a JSON object not being the original order.

What about the elements of JSON lists? Is their order maintained?

5条回答
  •  名媛妹妹
    2020-11-22 12:50

    Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.

    This means that if you run either of the following:

    var animals = {};
    animals['dog'] = true;
    animals['bear'] = true;
    animals['monkey'] = true;
    for (var animal in animals) {
      if (animals.hasOwnProperty(animal)) {
        $('
  • ').text(animal).appendTo('#animals'); } }
  • var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
    for (var animal in animals) {
      $('
  • ').text(animal).appendTo('#animals'); }
  • You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.

    Demo here and here.

提交回复
热议问题