1

If I have an object an cycle through its properties:

var obj = {a: 1, b: 2, c: 3}

for (var prop in obj){
   console.log(obj[prop])
}

Will I inevitably always get: 1, 2, 3 as a result? On what it may depend? Is other result practically real?

4

1 回答 1

3

No, there is no guarantee in the language regarding the order of iteration in object properties.

From the MDN :

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)

and

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later 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 as one might expect after having deleted the property and then added it back.

So if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

If you want a guarantee, you have to use an array. You may construct it by sorting the property key if you like.

于 2013-03-19T09:35:55.690 回答