Google Chrome vs JavaScript

2010/6/1 23:16

For a while I've been stymied by a supposed bug in the Google Chrome browser: elements generated dynamically from objects are rendered in "random" order.

Take for instance this:

var months = {10: 'January', 25: 'February',
          3: 'March', 19: 'April',
          21: 'May', 89: 'June', 
          1: 'July', 32: 'August',
          55: 'September', 13: 'October',
          12: 'November', 7: 'December'};

var dest = document.getElementById('destinationDiv');
for(var i in months)
{
   var out = document.createElement('div');
   out.innerHTML = months[i];
   dest.appendChild(out);
}

Every major browser, even internet explorer 6, will render the following block as such:

    January
    February
    March
    April
    May
    June
    July
    August
    September
    October
    November
    December

In the order the elements were defined in the object. Chrome is the lone exception:

    July
    March
    December
    January
    November
    October
    April
    May
    February
    August
    September
    June

It turns out that Chrome pre sorts object with numeric associative keys. Of course there's probably nothing in any official spec that forces them to store an object as it was inserted, but this was the de facto standard for a decade, and means that in order to properly render the element, you'll need to apply a custom sort to your objects.

This seems like a bug made with the best intentions, like "man just imagine how much faster Chrome can render associative objects if we sort the keys during creation!" but in practice its just another hassle for developers.

So this is an error present in the Wurfl Browser off this site, one which I'll need to put in a fix for in due time.