Does JavaScript guarantee the order of object properties?
P粉287254588
P粉287254588 2023-08-17 17:04:41
0
2
509
<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>
P粉287254588
P粉287254588

reply all(2)
P粉186897465

Yes (but not always in insertion order).

Most browsers iterate over object properties in the following order:

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

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:

P粉478445671

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:

// 键的顺序: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 attributes 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