The order of looping through an object may be broken only during iteration?

亡梦爱人 提交于 2019-11-29 15:47:58

The MDN page on delete states that:

...all major browsers support an iteration order based on the earliest added property coming first... However, in the case of Internet Explorer, when one uses delete on a property [and] adds back a property with the same name, the property will be iterated in its old position -- not at the end of the iteration sequence...

Illustration:

var obj = {};

obj.x = 1; 
obj.y = 2;
obj.z = 3;

var a = [];
for(var i in obj) a.push(i);

delete obj.y;
obj.y = 2;

var b = [];
for(var i in obj) b.push(i);


document.write("1:" + a + "<br>2:" + b);

Chrome/FF/Safari display 1:x,y,z 2:x,z,y, while in MSIE (and Edge) the result is 1:x,y,z 2:x,y,z.

Note that unlike ES5, ES6 mandates that the properties must be iterated in the creation order:

For each own property key P of O that is a String but is not an integer index, in property creation order...

http://www.ecma-international.org/ecma-262/6.0/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys

The standard is not very clear what exactly "creation order" means. MS takes it that it's the initial creation time that matters, while others use the last creation time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!