Does JavaScript guarantee the order of object properties?
P粉287254588
2023-08-17 17:04:41
<p>If I create an object like this: </p>
<pre class="brush:php;toolbar:false;">var obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";</pre>
<p>Will the result object always look like this? </p>
<pre class="brush:php;toolbar:false;">{ prop1 : "Foo", prop2 : "Bar" }</pre>
<p>That is, are the properties in the same order as I added them? </p>
Yes (but not always in insertion order).
Most browsers iterate over object properties in the following order:
Some older browsers merge category 1 and category 2, iterating over all keys in insertion order. If your keys are likely to be parsed as integers, it's best not to rely on any particular iteration order.
Current language specification (since ES2015) Preserves insertion order, but varies browser behavior in case of keys that resolve to positive integers (e.g. "7" or "99") will vary. For example, Chrome/V8 does not respect insertion order when keys are parsed as numbers.
Old language specification (pre-ES2015) : Iteration order is technically undefined, but all major browsers adhere to the ES2015 behavior.
Please note that the behavior of ES2015 is a good example of language specifications being driven by existing behavior, not the other way around. For a deeper dive into this backwards compatibility way of thinking, see http://code.google.com/p/v8/issues/detail?id=164, which is a detailed introduction to Chrome iteration order Chrome bug reporting for behavioral design decisions. According to a (rather subjective) comment in this bug report:
Since ES2015, the iteration order of objects follows certain rules , but it does not always follow the insertion order . In short, the iteration order is a combination of insertion order for string keys and ascending order for numeric-like keys:
This can be better achieved using an array or
Map
object.Map
has some similarities toObject
, and is guaranteed to iterate keys in insertion order, without exceptions:It should be noted that before ES2015, the order of attributes in the object was not guaranteed at all. Object definition from ECMAScript 3rd Edition (pdf) :