问题描述
如果我创建一个这样的对象:
var obj = {};obj.prop1 = "Foo";obj.prop2 = "酒吧";
生成的对象会总是看起来像这样吗?
{ prop1 : "Foo", prop2 : "Bar" }
也就是说,属性的顺序与我添加的顺序相同吗?
对象的迭代顺序遵循一定的规则集
如果我创建一个这样的对象:
var obj = {};obj.prop1 = "Foo";obj.prop2 = "酒吧";
生成的对象会总是看起来像这样吗?
{ prop1 : "Foo", prop2 : "Bar" }
也就是说,属性的顺序与我添加的顺序相同吗?
对象的迭代顺序遵循一定的规则集
a> 从 ES2015 开始,但它并不(总是)遵循插入顺序.简单地说,迭代顺序是字符串键的插入顺序和数字键的升序的组合:
//键顺序:1, foo, barconst obj = { "foo": "foo", "1": "1", "bar": "bar";}
使用数组或Map
object 可以更好地实现这一点.Map
与 Object
和 保证键按插入顺序迭代,无一例外:
Map 中的键是有序的,而添加到对象中的键则不是.因此,当迭代它时,一个 Map 对象按插入的顺序返回键.(请注意,在 ECMAScript 2015 规范中,对象确实保留了字符串和符号键的创建顺序,因此遍历具有即只有字符串键的对象将按插入顺序生成键)
请注意,在 ES2015 之前,根本无法保证对象中的属性顺序.来自 ECMAScript 第三版 (pdf):
一个对象是一个成员类型对象.它是一个无序的属性集合,每个属性包含原始值、对象或功能.一个函数存储在对象的属性称为方法.
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?
The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order. Simply put, the iteration order is a combination of the insertion order for strings keys, and ascending order for number-like keys:
// key order: 1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }
Using an array or a Map
object can be a better way to achieve this. Map
shares some similarities with Object
and guarantees the keys to be iterated in order of insertion, without exception:
As a note, properties order in objects weren’t guaranteed at all before ES2015. Definition of an Object from ECMAScript Third Edition (pdf):
这篇关于JavaScript 是否保证对象属性顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!