4

why in IE7 javascript array.indexOf is not working? Here is one sample

function loaderFn()
{
    var arr=["0","1","2"];
    var b = arr.indexOf("1")
    alert("Index of 1 is "+b);
}

In IE7 in line 4 (arr.indexOf("1"))

Object doesn't support property or method 'indexOf' error throws

Why this hapening only in IE7? What is the way to find index no of a value in array using javascript for IE7?

Gowsikan
  • 5,571
  • 8
  • 33
  • 43
  • Check: http://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-ie-browsers – couchemar Mar 29 '13 at 08:53

1 Answers1

10

Add this in your document.ready method:

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

This is needed because IE does not include this method up to IE8. The above function checks if it exists, if not it extends the Array prototype with it.

Rob
  • 4,927
  • 12
  • 49
  • 54
  • for javascript, you need to write in `window.onload = function () { Javascript code goes here }` – Mohammad Arshad Alam Jan 15 '15 at 06:03
  • @Arshad That's not true in this case. The code you have given makes sure the DOM has been completely loaded. The javascript in my answer does not rely on the DOM, it extends the Array prototype if necessary. – Rob Jan 15 '15 at 07:23