JavaScript是否保证对象属性顺序? [英] Does JavaScript Guarantee Object Property Order?

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

问题描述

如果我创建这样的对象:

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中不保证对象中的属性顺序;你需要使用数组

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

ECMAScript Third Edition(pdf)


4.3.3对象



对象是$ b的成员$ b类型对象。 这是一个无序的属性集合,每个
包含一个原始值,对象或
函数。存储在对象的
属性中的函数称为
方法。

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.

自ECMAScript 2015 ,使用 地图对象可能是另一种选择。 Map Object 保证按键顺序


Map以插入顺序迭代其元素,而没有为Objects指定迭代顺序。

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

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

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