Does JavaScript guarantee the order of object properties?
P粉604848588
2023-08-20 17:42:13
<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 generated object always look like this? </p>
<pre class="brush:php;toolbar:false;">{ prop1 : "Foo", prop2 : "Bar" }</pre>
<p>That is, will the properties be 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 combine category 1 and category 2, iterating over all keys in insertion order. If your keys are likely to resolve to integers, it's best not to rely on any particular iteration order.
Current language specification (as of ES2015) Insertion order is preserved, but behavior for keys that resolve to positive integers (such as "7" or "99") varies between browsers different. For example, Chrome/V8 does not respect insertion order when keys resolve to 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 more in-depth look at this way of thinking about backwards compatibility, see http://code.google.com/p/v8/issues/detail?id=164, which is a detailed introduction to Chrome Chrome bug reporting for iterative sequential behavioral design decisions. According to one of the (rather subjective) comments in this bug report:
The iteration order of objects follows certain rules since ES2015, but it does not always follow the insertion order. Simply put, 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 properties in the object was not guaranteed at all. Object definition from ECMAScript 3rd Edition (pdf) :