Does JavaScript guarantee the order of object properties?
P粉604848588
P粉604848588 2023-08-20 17:42:13
0
2
491
<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>
P粉604848588
P粉604848588

reply all(2)
P粉894008490

Yes (but not always in insertion order).

Most browsers iterate over object properties in the following order:

  1. Positive integer keys are sorted in ascending order (as well as strings like "1" that parse to integers)
  2. String keys are in insertion order (ES2015 guarantees this and all browsers respect it)
  3. Symbol names are in insertion order (ES2015 guarantees this and all browsers respect it)

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:

P粉574695215

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:

// 键的顺序:1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }

This can be better achieved using an array or Map object. Map has some similarities to Object, 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) :

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template