Reputation: 3804
I'm currently use jquery 1.8.3. I think it added indexOf
to Array.prototype
so now every of my array always contains the method indexOf as the first element.
Doing for (var i in object)
I always get the method infexOf as my first element and it bugged my code.
Bug happened on IE8 only.
What I want is to remove this indexOf from all arrays or anyway to hack jquery / resolve this problem.
PS: I'm not even sure if it's jquery is the cause of this problem
Thanks.
Upvotes: 0
Views: 286
Reputation: 168853
The correct answer here is that you shouldn't be using a for(...in...)
loop to iterate an Array in Javascript.
The whole point of having an Array is that it has a numbered sequence of elements, so you should be using a for()
loop.
for(var i=0; i<myArray.length; i++) {
//do stuff here with myArray[i]
}
That alone will resolve the issue in this case, because it will only iterate the numbered elements, so the indexOf
method won't get involved.
However, a brief explaination of the problem with for(..in..)
here may be helpful, so let me explain...
The underlying cause of the error you're seeing is because the indexOf
method isn't supported for arrays in IE8, so something in your code (not jQuery though) has added it to the Array prototype.
This in turn means that when you do a for(..in..)
loop, it will be picked up as one of the elements to be iterated.
In this case, you have a better solution (the for()
loop; see above), but in cases where you really do need to use a for(..in..)
loop, this can be a real problem. You can prevent this by checking hasOwnProperty()
immediately inside your for(..in..)
loop. This function returns false
for items that are part of the object prototype, so it helps you avoid hitting unwanted methods when looping an object.
This is considered best practice for every for(..in..)
loop. In fact, if you use a tool like JSLint, to check your coding style, it will complain if you don't do this.
Upvotes: 1
Reputation: 45155
Aside from not using for...in
to iterate over an array, if you must use for...in
, then combine it with hasOwnProperty
to tell if the property you are looking at really belongs to the object in question, or came from the prototype:
for (var prop in myObject) {
if (myObject.hasOwnProperty(prop)) {
// this didn't come from the prototype.
}
}
Upvotes: 2