Coder Perfect

For Internet Explorer browsers, how to fix Array indexOf() in JavaScript

Problem

If you’ve worked with JavaScript for any length of time, you’re aware that Internet Explorer [including Internet Explorer 8] does not support the ECMAScript method for Array.prototype.indexOf(). It’s not a big deal because you can use the following code to enhance the functionality of your page.

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 encapsulate it with the following check on all of my pages, which checks if the prototype function exists and, if not, extends the Array prototype?

if (!Array.prototype.indexOf) {

    // Implement function here

}

Or run a browser check and if Internet Explorer is found, just use it?

//Pseudo-code

if (browser == IE Style Browser) {

     // Implement function here

}

Asked by Bobby Borszich

Solution #1

Do it this way…

if (!Array.prototype.indexOf) {

}

MDC has recommended compatibility.

Browser detection code is generally frowned upon.

Answered by Josh Stodola

Solution #2

You could also use the inArray function from jQuery 1.2, which should work in all browsers:

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

Answered by Moses Lee

Solution #3

The complete code would then be as follows:

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;
    }
}

Check out Stack Overflow’s Fixing JavaScript Array Functions in Internet Explorer for a comprehensive solution and code to this and other array functions (indexOf, forEach, etc.).

Answered by Luis Perez

Solution #4

instead you may use:

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

Answered by scotta7exander

Solution #5

You should use if (!Array.prototype.indexOf) to see if it’s not defined.

Also, your indexOf implementation is incorrect. In your if (this[i] == obj) line, you must use === instead of ==, otherwise [4,”5″]. According to your implementation, indexOf(5) should be 1, which is erroneous.

I recommend that you utilize the MDC implementation.

Answered by Eli Grey

Post is based on https://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-internet-explorer-browsers