Adding .indexOf() to arrays in Internet Explorer

Most of you will already know this but hey, it doesn’t hurt to tell the tale again.

Looking up an array elements value by key is trivial:

var bar = someArray['foo'];

In actually working javascript implementations the reverse is simple, too:

'foo' == someArray.indexOf(bar); //will be true after the above code snippet

The actual API docs can be found over at Mozilla.org.

However, there is still this one JavaScript engine that is not only broken beyond repair but also lacks important features in the first place. I’m talling, of course, about our beloved Interbet Explorer.

Trying to use someArray.indexOf() in up to IE8 will result in an error message telling you that the object does not support this method.

So, let’s fix this!

if (typeof Array.prototype.indexOf !== 'function') {
    Array.prototype.indexOf = function(value) {
        for (var idx in this) {
            if (this.hasOwnProperty(idx)) {
                if (this[idx] == value) {
                    return idx;
                }
            }
        }
        return -1;
    }
}

This will check, if the engine that your script is running on already has the indexOf() method, and if not, it will simply add it to the Array prototype and by that to all present and future arrays.

Not exactly a game changer, but useful.