Quantcast
Viewing latest article 9
Browse Latest Browse All 9

Google Chrome : array evals return out of order

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,6852nOrder 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!


Viewing latest article 9
Browse Latest Browse All 9

Trending Articles