开发者

Can chrome be forced to iterate "string numeric" keys in the order they are stored

I seem to be having an interesting problem only in chrome (not IE, FF). Given the following object:

var myObj = {
  "59" : "Hello",
  "52" : "and",
  "50" : "how",
  "31" : "are",
  "65" : "you"
};

Going over this object via a for loop spits out the contents in the following order:

for(var j in myObj) {  document.write(myObj[j] +', '); }

are, how, and, hello, you

All the other major browser give it in 'proper' order. Chrome is treating the keys as integers instead of strings. The problem is I have a json data source I can't change, an开发者_StackOverflow社区d I need to access the items in the order they're in the object.

Can anyone suggest a way to do this in Google Chrome?


When iterating over an object via for...in, the order of properties is not guaranteed. There is nothing you can do:

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 from the delete page:

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 would like to know why it is like that, feel free to read the very long discussion in the V8 Issue Tracker "Wrong order in Object properties interation":

http://code.google.com/p/v8/issues/detail?id=164

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜