gpt4 book ai didi

javascript - JavaScript 保证对象属性顺序吗?

转载 作者:行者123 更新时间:2023-11-28 07:33:33 24 4
gpt4 key购买 nike

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

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

生成的对象总是看起来像这样吗?

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

也就是说,属性的顺序是否与我添加它们的顺序相同?

最佳答案

对象的迭代顺序如下 a certain set of rules自 ES2015 以来,但它并不(总是)遵循插入顺序。简单地说,迭代顺序是字符串键的插入顺序和类似数字的键的升序的组合:

// key order: 1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }

使用数组或 Map object可能是实现这一目标的更好方法。 MapObjectguarantees the keys to be iterated in order of insertion 有一些相似之处,无一异常(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)

需要注意的是,在 ES2015 之前根本无法保证对象中的属性顺序。对象的定义来自 ECMAScript Third Edition (pdf) :

4.3.3 Object

An object is a member of thetype Object. It is an unordered collection of properties each of whichcontains a primitive value, object, orfunction. A function stored in aproperty of an object is called amethod.

关于javascript - JavaScript 保证对象属性顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com