Monday, December 29, 2008

[jQuery] Re: What is IE7 barfing at this js?

Never use a for..in loop to iterate over an array.
 
Without seeing the code in the context of a running test page, I can't tell you why IE is seeing a bogus element in the array, but I can speculate that some other code elsewhere in the page is adding a method to Array.prototype in IE only. That method would be enumerated during the for..in loop.
 
You can fix this by using a proper technique to loop through the array. You could use $.each, or a "for( i = 0, n = data.length;  i < n;  i++ )" loop. Or, since you know the array doesn't contain any null elements, here's my favorite technique (along with a couple of other minor improvements):
function loadResults(data) {
  var OPT_VOTES = 2;
  var total_votes = 0;
 
  for( var item, i = -1; item = data[++i]; ) {
    votes = +item[OPT_VOTES];
    total_votes += votes;
    alert( "total_votes=" + total_votes + " --- " + votes );
  }
}
-Mike


From: Bruce MacKay
Hi folks,

The following snippet processes a JSON string sent back to the browser (it is part of a poll)

function loadResults(data) {
  var OPT_VOTES = 2;
  var total_votes = 0;
 
  for (id in data) {
    total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
                  alert("total_votes="+total_votes+" --- " + data[id][OPT_VOTES]);
  }
}

The JSON string looks like this...

[["1","High cost","23","What is the biggest challenge to recycling irrigation water?"],["2","Disease and algae management","12","5"],["3","Plentiful and cheap water","8","4"]]  
The problem I'm having is that IE7 appears to see 4 rows in the array - and consequently returns "total_votes=NaN --- undefined" at the first alert and "total_votes=NaN --- 23" at the second loop and so on.

FF, Opera, and Safari all handle the code without problem - can anyone help me understand what IE7 is getting upset about?

Thanks,

Bruce

No comments: