/array, bug, fix, ie, index, indexOf, JavaScript

JavaScript, return index of an element in array

Recently I’ve been working on a project with HTML5's <video> tag event handling and I needed to check if an element exists in the array. Quick googling resulted in neat native JavaScript method Array.indexOf. It returns the first index at which a given element can be found in an array, or -1 if it is not present. It all worked just fine in Firefox, Chrome and such.
Why wasn’t I surprised when my script behaved a bit weird in Internet Explorer. After many hours of "fun" with IE JavaScript debugger, I found that none of IE versions support the Array.indexOf method.

Thanks to this post I was able to quickly fix it by adding below code to my script.

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

and the world was beautiful again.