Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - JavaScript是否保证对象属性顺序?(Does JavaScript Guarantee Object Property Order?)

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?(也就是说,属性的顺序是否与我添加它们的顺序相同?)   ask by mellowsoon translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order .(自ES2015起,对象的迭代顺序遵循一组特定的规则 ,但不(始终)遵循插入顺序 。)

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对象可能是实现此目的的更好方法。) Map shares some similarities with Object and guarantees the keys to be iterated in order of insertion , without exception:(MapObject有一些相似之处,并保证按插入顺序对键进行迭代 ,无一例外:) The keys in Map are ordered while keys added to object are not.(Map中的键是有序的,而添加到对象中的键则没有顺序。) Thus, when iterating over it, a Map object returns keys in order of insertion.(因此,在对其进行迭代时,Map对象将按插入顺序返回键。) (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)((请注意,在ECMAScript 2015规范中,对象确实保留了字符串键和符号键的创建顺序,因此仅使用字符串键遍历对象会按插入顺序产生键)) As a note, properties order in objects weren't guaranteed at all before ES2015.(请注意,在ES2015之前根本无法保证对象中的属性顺序。) Definition of an Object from ECMAScript Third Edition (pdf) :(ECMAScript第三版(pdf)中对象的定义:) 4.3.3 Object(4.3.3对象) 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.(存储在对象属性中的函数称为方法。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...