遍历对象的顺序可能仅在迭代期间被破坏?

2022-01-24 00:00:00 object iteration javascript for-in-loop

我猜循环对象的首选方式是这样的:

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 循环以 任意顺序 迭代对象的属性(请参阅 delete 运算符了解更多关于为什么不能依赖迭代的表面顺序,至少在交叉浏览器设置).

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:

对于O的每个自己的属性键P,它是一个字符串但不是整数索引,按属性创建顺序...

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 认为重要的是 initial 创建时间,而其他人使用 last 创建时间.

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.

相关文章