Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

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

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 says that

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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...