How to fix Array indexOf() in JavaScript for Internet Explorer browsers – Dev

The best answers to the question “How to fix Array indexOf() in JavaScript for Internet Explorer browsers” in the category Dev.

QUESTION:

If you have worked with JavaScript at any length you are aware that Internet Explorer does not implement the ECMAScript function for Array.prototype.indexOf() [including Internet Explorer 8]. It is not a huge problem, because you can extend the functionality on your page with the following code.

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

When should I implement this?

Should I wrap it on all my pages with the following check, which checks if the prototype function exists and if not, go ahead and extend the Array prototype?

if (!Array.prototype.indexOf) {

    // Implement function here

}

Or do browser check and if it is Internet Explorer then just implement it?

//Pseudo-code

if (browser == IE Style Browser) {

     // Implement function here

}

ANSWER:

Alternatively, you could use the jQuery 1.2 inArray function, which should work across browsers:

jQuery.inArray( value, array [, fromIndex ] )

ANSWER:

Do it like this…

if (!Array.prototype.indexOf) {

}

As recommended compatibility by MDC.

In general, browser detection code is a big no-no.

ANSWER:

The underscore.js library has an indexOf function you can use instead:

_.indexOf([1, 2, 3], 2)

ANSWER:

The full code then would be this:

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

For a really thorough answer and code to this as well as other array functions check out Stack Overflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.).