Does JavaScript and / or JSON parsers need to list attributes in the order of definition?

Given the definition of an object:

var o = {x :1, y:2, z: 3, b: 4, a: 5, m: 6, X: 7}; 

At enumeration time, Chrome seems to follow the order in which the attributes are defined:

 for (var i in o) { console.log(i, o[i]); } 

Productivity:

 x 1 y 2 z 3 b 4 a 5 m 6 X 7 

Does JavaScript and / or JSON indicate this level of preservation?

In any case, is it reliable?

+6
source share
2 answers

No, Javascript specifications do not explicitly require any specific enumeration order; they are, by definition, disordered.

See section 12.6.4 of the ECMAScript specification :

The mechanics and order of listing the properties ... are not specified.

+9
source

There is no guarantee that the properties will be displayed in the order in which they are defined.

Some browsers will save the properties in the order in which they are defined, while others will not.

A JSON parser that parses JSON into something other than a Javascript object can preserve order from the source, otherwise it cannot be guaranteed.

+1
source

Source: https://habr.com/ru/post/946724/


All Articles