1

Possible Duplicate:
Why doesn't indexOf work on an array IE8?

I recently developed a script that uses native Javascript and jQuery. Most of my development has been with IE 9, Chrome, Firefox. For all of them the line below works perfectly:

if(data.cols.indexOf("footprint") < 0)

However today I pushed a bit of my code to a production system and a couple of the clients have come back saying their pages are broken. I have narrowed my search down to indexOf, which apparently IE 8 does not like in the slightest. So I am trying to find an alternative and I found this bit Array.prototype.indexOf but I am not really sure how I would tie that into an if-else similar to above.

Also if there is a better alternative then I am all ears. Also, is this something I may have to apply to IE 8 browsers only, where if IE 8 is found, use this, if not use the original?

Community
  • 1
  • 1
chris
  • 36,115
  • 52
  • 143
  • 252
  • 5
    Array.prototype.indexOf was first supported in IE9, see [this page on MDN](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf) for code you can include to support older versions of IE – MrOBrian Jul 12 '12 at 18:43

1 Answers1

1

This question has come up many times, another Stackoverflow thread can be found here: How to fix Array indexOf() in JavaScript for Internet Explorer browsers

Several people on different threads have recommended using this code from MDC. This appears to be the code:

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

    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;
  };
}

Just run this code before making any calls indexOf()

Community
  • 1
  • 1
Luis Perez
  • 27,650
  • 10
  • 79
  • 80