I just want to make others aware of a little quirk with Google Chrome’s Javascript engine (V8), eval’d associative JSON arrays (aka objects) are returned in the incorrect order . The problem is that the engine doesn’t do what a programmer would expect it to do, but the programmer should be aware of why its happening and that it does happen.
Basically, take the following psuedo associative array/object and its corresponding JSON version:
Psuedo Associative array
Array (
3503 => '',
3847 => '',
6852 => ''
);
JSON Array
var data = {3503:'',3847:'',6852:''};
Pretty basic huh? But that happens when we loop over this array/object? In Firefox, Safari and IE we get the same result, which is the array elements in the order listed above. Chrome on the other hand returns the items out of order. Now I know you are probably thinking, “its an array/object, order doesn’t matter”. This is technically true, but not if you are relying on the order for some reason, then you might find bugs cropping up. Check out the code below:
var data = {3503:'',3847:'',6852:''};
var s = '';
for(var i in data) {
s += i + ',';
}
alert("Expected order: 3503,3847,6852\nOrder observed: " + s)
Firefox, Safari and IE all return the following alert:
Expected order: 3503,3847,6852 Order observed: 3503,3847,6852
Chrome on the other hand returns this:
Expected order: 3503,3847,6852 Order observed: 6852,3503,3847
Weird! Give it a try in your current browser by clicking here
Javascript guru, John Resig, has posted a note about this:
http://ejohn.org/blog/javascript-in-chrome/
Or for the official bug reports:
http://code.google.com/p/v8/issues/detail?id=6
http://code.google.com/p/chromium/issues/detail?id=883
As always with javascript programming, expect the unexpected… and…
Be Warned!
Tags: browser, bug, chrome, google, javascript
this is very paintfull bug, we have got big issues in our JS/JSON powered sw :(
Hope they will fix it soon.
We have seen many bugs come and go when using google chrome. I think they still need to do some testing and work out the glitches before this can become a competitive browser.
It’s not that surprising, IMHO.
Javascript is the only language I’m aware of that actually does sort hash table keys. In every other language, order is undefined due to the way hash tables work.
If Javascript returns keys in sorted order, then they’re making a behind-the-scenes call to sort(), which adds extra processing.