Array.indexOf in Internet Explorer < 9


Our favorite Web-Browser in the whole wide world does support Array.indexOf, at least in the latest version (9.x). But previous version do not implement that feature, and apparently justifiably so.

As Soledad Penadés correctly stated (back in 2007), Array.indexOf has been around for quite some time in almost every browser, but it had never been standardized by the ECMA, until ECMAScript 5th Edition which was released in December 2009 (for comparison, IE8 was released in March, 2009).

Now one can argue that since it has been a de-facto standard for a while, Microsoft could’ve implemented it even though it hadn’t been standardized, but Microsoft’s policy seems to be that they only implement what is standardized, and that is not a bad policy at all (unfortunately, they don’t seem to be very good at implementing the standards either), so in this case I think the ECMA is the culprit, because it needed 12 years to add this very useful method to the standard.

A workaround is provided by the Mozilla Developer Network, as a reference implementation of the algoritm specified in the Standard ECMAScript 5th Edition:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}