Tuesday, March 1, 2011

How to fix Array indexOf() in JavaScript for IE browsers

If you have worked with JavaScript at any length you are aware that IE does not implement the ECMAScript function for Array.prototype.indexOf() [including IE8]. 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;
}

What I am looking for is 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 IE then just implement it?

//pseudo-code

if(browser == IE Style Browser) {

     // implement function here

}
From stackoverflow
  • Do it like this...

    if (!Array.prototype.indexOf) {
    
    }
    

    As recommended compatibility by MDC.

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

    Bobby Borszich : I don't have enough rep to edit the question but feel free to remove the ECMAScript lingo and replace with the appropriate wording. Thanks Again
    Pablo Cabrera : Be careful if you use this kind of detection. Another library might implement this function before you test it, and it might not be standards compliant (prototype has done it a while ago). If I were working in a hostile environment (lots of other coders using lots of distinct libraries), I wouldn't trust any of these...
  • You should check if it's not defined using if (!Array.prototype.indexOf).

    Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

    I recommend you use the implementation on MDC.

    Pablo Cabrera : Actually, it would be 1...

0 comments:

Post a Comment