Does JavaScript Guarantee Object Property Order?

2018-12-30 22:02发布

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?

标签: javascript
8条回答
琉璃瓶的回忆
2楼-- · 2018-12-30 22:43

From the JSON standard:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

(emphasis mine).

So, no you can't guarantee the order.

查看更多
只若初见
3楼-- · 2018-12-30 22:45

In modern browsers you can use the Map data structure instead of a object.

Developer mozilla > Map

A Map object can iterate its elements in insertion order...

查看更多
登录 后发表回答