Is the order of object properties guaranteed in JavaScript?
P粉663883862
P粉663883862 2023-10-12 20:05:36
0
2
494

If I create an object like this:

var obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";

Does the generated object always look like this?

{ prop1 : "Foo", prop2 : "Bar" }

That is, are the properties in the same order as I added them?

P粉663883862
P粉663883862

reply all(2)
P粉006977956

is (but not always in insertion order).

Most browsers iterate over object properties as:

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

Some older browsers combine categories #1 and #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 will be preserved, except for keys that resolve to positive integers (e.g. "7" or "99"), in which case browser behavior will vary. For example, Chrome/V8 does not consider insertion order when keys resolve to numbers.

Old Language Specification (Pre-ES2015) : The iteration order is technically undefined, but all major browsers adhere to the ES2015 behavior.

Note that the ES2015 behavior is a good example of a language specification being driven by existing behavior, not the other way around. For a deeper understanding of the backwards compatibility mentality, see http:// code.google.com/p/v8/issues/detail?id=164, a Chrome bug detailing Chrome iterations The design decisions behind sequential behavior. According to one of the (rather opinionated) comments on the bug report:

P粉541565322

Since ES2015, the iteration order of objects follows a specific set of rules , 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:

// key order: 1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }

Using an array or Map object is probably a better way to achieve this. Map with Object and are guaranteed to iterate keys in insertion order, without exception:

It should be noted that before ES2015, the order of properties in the object was not guaranteed at all. The definition of object comes from ECMAScript 3rd Edition (pdf):

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