.indexOf function on an array not working in IE7/8 using JavaScript

On IE<9 indexOf() it is not “well” implemented. Try to add this function on your code :

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

It will “replace” the original function, if not found in the ECMA-262 standard.

Leave a Comment