JavaScript 是否保证对象属性顺序? [英] Does JavaScript guarantee object property order?

查看:67
本文介绍了JavaScript 是否保证对象属性顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个这样的对象:

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 可以更好地实现这一点.MapObject保证键按插入顺序迭代,无一例外:

<块引用>

Map 中的键是有序的,而添加到对象中的键则不是.因此,当迭代它时,一个 Map 对象按插入的顺序返回键.(请注意,在 ECMAScript 2015 规范中,对象确实保留了字符串和符号键的创建顺序,因此遍历具有即只有字符串键的对象将按插入顺序生成键)

请注意,在 ES2015 之前,根本无法保证对象中的属性顺序.来自 ECMAScript 第三版 (pdf):

<块引用>

4.3.3 对象

一个对象是一个成员类型对象.它是一个无序的属性集合,每个属性包含原始值、对象或功能.一个函数存储在对象的属性称为方法.

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:

The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion. (Note that in the ECMAScript 2015 spec objects do preserve creation order for string and Symbol keys, so traversal of an object with ie only string keys would yield keys in order of insertion)

As a note, properties order in objects weren’t guaranteed at all before ES2015. 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.

这篇关于JavaScript 是否保证对象属性顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆