Question: I have defined prototype for Array indexOf ( to support array indexOf in Internet Explorer )

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

```

When I am creating array with values [1,2,3], this indexOf code snippet added into the Array like below

```
["1","2","3",function(obj){for(var i=0;i<this.length;i++){if(this[i]==obj){return i;}}return -1;}]

```

This problem happens only in IE.

Can anyone help me to resolve this issue. Thanks in advance.

---

I didn't use `for...in` loop anywhere, for this I am using jQuery sortable toArray method `.sortable("toArray");`.

Answer: 
I am assuming that at some point you are using a `for...in` loop to iterate over the elements of your array. For example:

```
for (var elem in myArray) {
    //Do stuff...
}

```

A `for...in` loop will enumerate all enumerable properties of an object, including those it has inherited from it's ancestors in its prototype chain. You've added a method to the `Array` prototype:

```
Array.prototype.indexOf = function(obj){ //...

```

This property is enumerable (you can't define non-enumerable properties - see [`Object.defineProperty`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty) - in older versions of IE), so a `for...in` loop will include this property.

The simple solution is to **never use a `for...in` loop to iterate over an array**! Use a normal `for` loop instead.
Your problem is that your new `indexOf()` method is marked "enumerable." Unfortunately, there is no fix for this in IE7 or non-standards-mode IE8. But you can at least patch the issue for standards mode IE8 by using some ES5 trickery. Modify your code to look like this and it should get rid of the extra element if you're in IE8 standards mode:

```
(function () {
    var indexOfFn = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
               return i;
            }
         }
         return -1;
    };

    if(!Array.prototype.indexOf){
        if(typeof Object.defineProperty === "function") {
            Object.defineProperty(Array.prototype, "indexOf", {
                value: indexOfFn,
                enumerable: false
            });
        } else {
            Array.prototype.indexOf = indexOfFn;
        }
    }
}());

```

I know it's wordy, so it might not be worth the effort. But it will also protect your JavaScript from other people's bad coding where they might end up using an Array with a for-in loop.