javascript – 循环遍历对象的顺序可能只在迭代期间被破坏?
作者:互联网
我想循环一个对象的首选方法是这样的:
for (var prop in obj) {
if( obj.hasOwnProperty( prop ) ) {
console.log("obj." + prop + " = " + obj[prop]);
}
}
MDN说
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).
因此,如果我在迭代期间不修改对象属性,我可以保证正确的顺序,即键/属性在对象中出现的顺序,或者此语句是否意味着其他内容?
解决方法:
…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.
请注意,与ES5不同,ES6要求必须按创建顺序迭代属性:
For each own property key P of O that is a String but is not an integer index, in property creation order…
07001
标准不是很清楚“创造顺序”究竟是什么意思. MS认为这是重要的初始创建时间,而其他人使用上次创建时间.
标签:for-in-loop,javascript,object,iteration 来源: https://codeday.me/bug/20191002/1845199.html