Creative Juices Bo. Co.

Satisfy Your Thirst For Something Refreshing!

indexOf problems in Internet Explorer

Reason #592 why I hate Internet Explorer

My last step on any website design is to go through it and make sure that it works and look correct in the various flavors of Internet Explorer. I can't really say that the time spent doing this is blissful. I compare it to going to the dentist, because I never know what I'm going to find and when I do it's rarely good.

So today as I was debugging, what I thought was a very simple, JavaScript page. I came across one of those nifty "This method or function is undefined" errors from the Internet Explorer debugger. And as we all know, the IE debugger is as worthless as playing "I Spy" with a blind person.

So what was the problem? Well it turns out that IE doesn't like indexOf for arrays. I did a little research and I came across a fix online from Soledad Penades Blog. Basically, we need to test if the indexOf method is defined for Arrays. If not, then use the much loved JavaScript prototype function to create it, like so:

if(!Array.indexOf){
   Array.prototype.indexOf = function(obj){
      for(var i=0; i<this.length; i++){
         if(this[i]===obj){
            return i;
         }
      }
      return -1;
   }
}

Hope this helps anyone with the same problem, and thanks Soledad!