Javascript: array.indexOf() fix for IE8 and below

Just a quick note on how to deal with another one of the IE/Javascript deficiencies that make our lives so much easier(!) – IE from versions 8 backwards doesn’t support the indexOf() function for arrays, e.g.

var myArray = ['Apple','Banana','Orange'];
alert(myArray.indexOf('Orange'));  //alerts '2', but not in IE <=8

Thankfully, there are easy ways to fix this:

  1. the JQuery $.inArray() function, e.g.
    alert($.inArray('Orange',myArray);
  2. Defining the indexOf function (before you call it!) if it doesn’t exist – taken from MDN
    if (!Array.prototype.indexOf) {
      Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        'use strict';
        if (this == null) {
          throw new TypeError();
        }
        var n, k, t = Object(this),
            len = t.length >>> 0;
    
        if (len === 0) {
          return -1;
        }
        n = 0;
        if (arguments.length > 1) {
          n = Number(arguments[1]);
          if (n != n) { // shortcut for verifying if it's NaN
            n = 0;
          } else if (n != 0 && n != Infinity && n != -Infinity) {
            n = (n > 0 || -1) * Math.floor(Math.abs(n));
          }
        }
        if (n >= len) {
          return -1;
        }
        for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) {
          if (k in t && t[k] === searchElement) {
            return k;
          }
        }
        return -1;
      };
    }

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.