循环遍历对象的顺序可能只在迭代期间被破坏? [英] The order of looping through an object may be broken only during iteration?

查看:180
本文介绍了循环遍历对象的顺序可能只在迭代期间被破坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想循环一个对象的首选方法是:

I guess the preferred way of looping through an object is this:

for (var prop in obj) {
  if( obj.hasOwnProperty( prop ) ) {
    console.log("obj." + prop + " = " + obj[prop]);
  } 
}

MDN说


已删除,添加或修改的属性
for ... in循环遍历中对象的属性任意顺序(有关为什么不能依赖迭代的看似有序性的原因,请参阅删除运算符,至少在跨浏览器设置中)。

Deleted, added or modified properties A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).

因此,如果我在迭代期间不修改对象属性,我可以保证正确的顺序,即键/属性出现的顺序在一个对象或这个语句中意味着什么呢?

So if I don't modify object properties during iteration I can be guaranteed the correct order i.e. the order in which keys/properties appear in an object or this statement means something else?

推荐答案

删除时的MDN页面说明:


...所有主流浏览器都支持基于最早添加的属性的迭代顺序...但是,对于Internet Explorer,当一个人在属性上使用delete时[和]添加一个具有相同名称的属性,该属性将在其旧位置迭代 - 而不是在迭代序列的末尾...

...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...

插图:

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显示 1:x,y,z 2:x,z,y ,而在MSIE(和Edge)中,结果是 1:x,y,z 2:x,y,z

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.

请注意,与ES5不同,ES6要求必须按创建顺序迭代属性:

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


对于每个属性的键P,它是一个String但不是整数索引,在属性创建顺序中...

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

标准不是很清楚创造顺序究竟是什么意思。 MS认为初始创建时间很重要,而其他人使用最后创建时间。

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.

这篇关于循环遍历对象的顺序可能只在迭代期间被破坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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