Does JavaScript Guarantee Object Property Order?

If I create an object like this:

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

Will the resulting object always look like this?

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

That is, will the properties be in the same order that I added them?


No, properties order in objects is not guaranteed in JavaScript; you need to use an Array .

Definition of an Object from ECMAScript Third Edition (pdf):

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Since ECMAScript 2015 , using the Map object could be an alternative. A Map shares some similarities with an Object and guarantees the keys order:

A Map iterates its elements in insertion order, whereas iteration order is not specified for Objects.


Current Language Spec : technically, order is unspecified.

Current Browsers : order is preserved with the major exception of keys like "7" that parse as integers and are handled differently by Chrome/V8.

Future Language Spec (>ES2015) : Generally, you can expect that things ordered today will not become unordered. New APIs will guarantee order; existing APIs are difficult to change. See JMM's answer for more details.

The best link below is in Tim Down's comment:

http://code.google.com/p/v8/issues/detail?id=164

That bug covers in detail the design decisions involved for Chrome's implementation of key ordering. One take-away is that for string keys that don't parse to an integer (ie "a" or "b", but NOT "3"), keys are printed in insertion order on all major browsers and while this behavior is not "standardized", it IS considered a significant backwards-compatibility issue by browser vendors. Use at your own risk.

Per one of the (rather opinionated) comments:

Standards always follow implementations, that's where XHR came from, and Google does the same thing by implementing Gears and then embracing equivalent HTML5 functionality. The right fix is to have ECMA formally incorporate the de-facto standard behavior into the next rev of the spec.

If you rely on insertion order, you are outside the ECMAScript spec, but within the de-facto standard of common browser behavior as long as your keys don't parse as integers.


At the time of writing, most browsers did return properties in the same order as they were inserted, but it was explicitly not guaranteed behaviour so shouldn't have been relied upon.

The ECMAScript specification used to say:

The mechanics and order of enumerating the properties ... is not specified.

However in ES2015 and later non-integer keys will be returned in insertion order.

链接地址: http://www.djcxy.com/p/95304.html

上一篇: 如何获取javascript对象的方法名称?

下一篇: JavaScript保证对象属性顺序?