Array.indexOf in Internet Explorer

According to this document at Mozilla Developer Center, Javascript 1.5 has been implemented in a browser since at least the first releases of Mozilla as open source browser, which means, in other words, since around 1998. Let’s assume it was 2002 which is marked as the release of the 1.0 version.

And I was doing some interface programming lately and I needed to check if an element was in an array. Went to Gecko’s documentation (that’s the one I normally use, since it’s less overbloated with crappy ads) and checked that Array objects had an indexOf function. Cool! I used that function on my code. Then once I finished with all the development, went to The Horror (i.e. Internet Explorer) and tested it.

Surprise! It was broken! What had I done? (You know the debugger for Internet Explorer is not specially helpful)

I suspected of the indexOf function, and recalled vague memories about doing a custom search function in the past for looking into arrays and not having to write a for(i=0; i<ar.length;i++) thing each time…

Mmmm… did a alert(‘Array.indexO’) in ie and what did I get?: undefined

So they have been spent five years for releasing ie7 and still they didn’t implement Array.indexOf!

No worries, though. Javascript is flexible! Look, IE, I don’t care if you choke on the mere seeing of indexOf, you’re going to run it whether you like it or not!

	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 voila! my script wasn’t broken anymore!

68 Responses to “Array.indexOf in Internet Explorer”

  1. herotyc says:

    I was just curious about the way mootools handled this(to be compatible with IE):

    http://svn.mootools.net/tags/1-10/Native/Array.js

    It’s just like you did. Btw, have you tried mootools? “will make you happier” :D

  2. sole says:

    Funny! I was wondering if there could be a better way of doing it but I was in a rush… I haven’t played yet with mootools, since I started with jquery and didn’t want to go back and rewrite that project with mootools :)

    But I have something in mind and will probably have a look at moo for that project just before starting to code in jquery like crazy!

  3. blackpawn says:

    whoa that’s crazy.. how could they have missed that?? hmm maybe it’s missing to incentivize you to use VBScript instead! ;)

  4. sole says:

    yay no! no vbscript!

    Which reminds me something that happened to me past year: i wanted to look for some information about rugsacks on an sports retailer site and began to click everywhere in the menu, with no luck. Nothing was happening, and I couldn’t see any Javascript error in the debug console. I thought it might be some IE only stuff going on there, but before abandoning completely, I took a look at the source and guess what!

    All the navigation was built with VBScript! I couldn’t believe it, and the worst of all is that the page was quite recently built. Absolutely fascinating.

  5. Kr0n says:

    Nice!

    To improve it even more:

    When prototyping, the new method should extend all the functionality of the existing method, in order to use it completely transparent. In this case, the “start” parameter is missing. Obviously, no such a big deal but being perfectionists… ;)

  6. jo says:

    Mozilla provide the full javascript implementation for compatibility:
    http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf

  7. scott says:

    That you for publishing this find, you saved me!

  8. Nick Mudge says:

    Good stuff. Thanks.

  9. sole says:

    Thanks Nick, it’s a big compliment coming from you – I have been reading your blog and it’s got loads of interesting notes and thoughts.

  10. Gargaj says:

    (What irony that I search for the same thing and end up here, eheh)

    Apparently, it’s not part of the DOM anyway: http://www.w3schools.com/jsref/jsref_obj_array.asp :( (had the same problem with Opera)

  11. sole says:

    I own your internets!!!! HAHA!

    No, really. I guess it’s something more of a de-facto standard, or an ECMA Script standard. Or simply a common sense standard. Whatever! :-)

  12. Stan says:

    Nice fix, this had me stumped for a while with some validation which was working fine in Firefox but borked in IE.

    Cheers!

  13. Kemot says:

    Great! It helped me a lot. Thanks.

  14. sole says:

    Great to read that :)

  15. bob says:

    Thanks for this – ! I was scratching my head over why my indexOf wasn’t working also. Good to see someone is one step ahead of Bill Gates.

  16. Shawn Welch says:

    Hey, you are cute. Thanks for the tip. IE 7 blows!!!

  17. Raphael says:

    Thanks.
    That’s exactly what I was looking for.

  18. sole says:

    No problem. I wonder if this will be fixed in IE8 … might check it…

  19. Google rank 1 for ‘ie indexof array’, not bad ; ).

    I just hoped for a second this was working in IE, but I guess we’ll have to wait for 2012 the year when IE ends … : ).

  20. sole says:

    Oh, mighty Felix “thinking php” Geisendörfer here :)

    Yes we come to expect lots of things even on newer versions such as IE7 but it’s still as buggy as usual. Now I always assume it won’t work, and maybe it will surprise me later :D

  21. webdesign says:

    Wow thanx i was really stuck with this piece of javascript !! have spent several hours check IE and FF for what is wrong :) Thx again

  22. Manoj Mathai says:

    Thanks man, that helped

  23. M1ke says:

    Thanks a lot for this – been banging my head against a wall trying to translate a nice working Firefox site into something other than a static lump in Internet Explorer. Eventually realised that it was hating indexOf and Googled – came straight here!

  24. sole says:

    Super :)

  25. Audren Cezar says:

    Thx, very good trick! ;)

  26. yves geunes says:

    I ran into the same problem. This solved it:

    myString=Array.toString();
    theIndex=myString.indexOf(“something”);

  27. Mmm. When you look at something like http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf you have to keep an eye out for that “ECMAScript Edition: none” tag! I was caught out myself by indexOf this week.

    This and others are in the proposals for ECMAScript 4 – http://wiki.ecmascript.org/doku.php?id=es3.1:targeted_additions_to_array_string_object_date&s=indexof – but don’t expect to see anything interesting before (or soon after!) October 2008.

    @yves geunes: myString.indexOf(“something”); isn’t going to achieve the same thing, unless you know that “something” contains no commas etc which could match element boundaries. It’s conceptually not the same search.

  28. sole says:

    @James – you’re right on the ECMAScript edition “little detail”, and on clarifying yves solution too. I was going to comment on that but I haven’t had time these past days.

    In any case… six years and there’s still no support for it in IE? :-) They followed the ‘defacto’ standard with the tabs in IE7, but they gave no love to the scripting engine it seems :-)

  29. @yves geunes
    Array.toString()

    The toString() is ok but you could also use the join() method like this:
    arrayObject.join().indexOf(“look for”)

    Just one warning, it is best to use this only for “single caracter” array elements like in:
    var arrayObject = new Array(“a”,”b”,”c”);

  30. Adam says:

    Thank you so much. This article saved my project! :)

    Stupid IE…

  31. thirdender says:

    Found your site through Google search… Was playing with the awesome PersistJS library (http://pablotron.org/?cid=1557) and it wigged out when the ‘remove’ function tried indexOf on an Array. I guess I’m supposed to be using Prototype or something to smooth the IE glitches… :-P

  32. Julie says:

    This saved me too!

  33. Dale says:

    Holy cannoli, Soledad, you saved my butt. My navigation scripts worked great on FF, and my heart sank to see them dead in the water on IE. After a fruitless search for decent IE debug tools, I finally located the offending line…which included indexOf. Googled “javascript indexOf IE”, your site came up, and I pasted in that lovely little code snippet and I’m back in business.

    Blessings on your family. Dalegeist.com will, thanks to you, be up and running in the twinkle of an eye.

    Dale

  34. Venu says:

    Thanks a lot to publish this. It’s working great in IE and as well as in Mozilla. :)

  35. Vijay Mohan says:

    hi
    its realy good workin well with little modification

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

  36. Marius says:

    Array.indexOf(value)

    Simple jQuery solution:
    jQuery.inArray(value, Array)

  37. Faseel says:

    extending the Array.prototype may work if you are only using Array.indexOf()
    but it breaks the Array object.

    the following will give unexpected results on IE if the Array.prototype is extended.
    for(var i in data) will output the Array.indexOf function as well.
    log: function (data) {
    for (var i in data){
    console.log(data[i].string);
    }
    }
    },
    if the Array is extended, then a typeof check is required before performing any operation with arrays.

  38. Switch says:

    Thanks man, this was VERY helpful! Stupid IE!

  39. sole says:

    hihihi :)

  40. m says:

    Thanks great fix!

    Just one more reason to stop using IE!

  41. Greg says:

    Nice, this helped me a lot.

    IE was driving me up a wall.

  42. Pascal says:

    Hey. Thanks a lot. Just ran into the same problem…

  43. SP says:

    Wasted one whole day, thinking I am missing something in the code, but line by line debugging uncovered this issue,

    Thx

  44. sole says:

    Yeah it’s something odd isn’t it? You can’t believe it’s a failure in the browser’s engine and tend to blame your code :)

  45. [...] Sure enough I turn to my search pal Google and realise that I am not the first to encounter this error. IE (even version 7) does not implement Array.indexOf….. Can’t believe I have not [...]

  46. lean says:

    Thanks, you saved me a lot of time

  47. marko says:

    thanks for this. it helps a lot.

  48. [...] Array.indexOf() function I have gave me the idea to extend the prototype of the HTMLElement object so I could have [...]

  49. Aamir Afridi says:

    Thank for this nice tip. I am using jQuery and i just found this :
    http://docs.jquery.com/Utilities/jQuery.inArray
    Which solves my problem :)

  50. sole says:

    Yep, but if you don’t use jQuery you can use the other ‘fix’ ;)

  51. Lidya Agustina says:

    Cool! save my day!

  52. thnk4yrslf says:

    Amazing script, it’s a kinda magic!

    Gracias Sole.

  53. yegle says:

    stupid software…stupid bug…I cost about an hour on this problem…

  54. sole says:

    Yes, I’m looking forward to the day we can all forget about IE’s stupid bugs :)

  55. Francesco says:

    Thanks very, very, very much …

  56. sole says:

    No problems! :) hope you enjoy the fix :D

  57. Penny says:

    Thanks, it saved me!

  58. [...] 那么是什么问题呢?那么结果是不喜欢IE浏览器的阵列indexOf。我做了小小的研究,我碰到一个固定在线来自Soledad Penades Blog。基本上,我们需要测试是否IndexOf方法是数组。如果没有,然后使用广受欢迎的JavaScript函数来创建原型一样,所以: 1 2 3 4 5 6 7 8 9 10 if(!Array.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]===obj){ return i; } } return -1; } } [...]

  59. dan kloke says:

    Thank you.

    What’s weird is that my (raw, un-prototype-fixed) indexOf usage worked for a while in IE8. Then it stopped. Huh? Your code fixed it of course.

    But apparently I added document.getElementById mixed in with otherwise pure jQuery, and once that happened started IE8 barfing on indexOf.

    Freaky. Whatever. Moving on..

    Thanks again.

  60. Rick says:

    Nice fix for a big hole in IE6 (hey that kinda rhymes!).

  61. sole says:

    Haha Rick :D

    If we had to devise rhymes for every IE6 fix…!

  62. Brillo… Thanks

  63. Jonas says:

    Thanks, was baffled by the fact it didn’t work out of the box :s

  64. Joe Plumber says:

    Note that the native indexOf() method is MUCH MUCH faster than looping through all the elements in an array via JavaScript

    Shameful that IE doesn’t support this basic method…

  65. MyFineDay says:

    Cool! Thank you.

  66. NotStandard says:

    Wait! You all are missing something! The Array indexOf() method is not part of the ECMAScript Edition 3 standard. It is specific to Firefox. Just because Firefox provides it, doesn’t mean that it’s standard. In this respect, IE follows the standard. By using indexOf(), you are actually writing non-standard code. That is the problem.

    The solution is not to use indexOf(), then your code will work anywhere, and is standard-compliant.

    Besides, the moment you add to the prototype in this manner, you break the standard “for(… in …)” statement, for all of the code in your page. We just moved to a new portal framework, and the vendor’s code just broke over 600 of our for-statements, because they quietly added these methods to the prototype. What a pain!

  67. sole says:

    Yes, mr. NotStandard, that has been commented prior to your comment. Anyway, as you might already know, there are many types of standards, and I think we could say that a feature that is implemented in EVERY BROWSER except IE can be considered a de facto standard.

    I never said it was an standard, anyway :P

Leave a Reply