Array indexOf implementation for Internet Explorer

前提是你 提交于 2019-12-06 03:53:56

That's because you edit Array.prototype and thus any array created inherits the custom-made VISIBLE method indexOf that the "in" command can see.

for..in construct in JavaScript doesn't act like for example PHP's foreach - it doesn't just iterate all the items in the array but also iterates all the methods and properties the array OBJECT might have (arrays in JavaScript are actually "disguised" objects). Native methods are invisible to the for..in construct but all the custom additions are not.

In your example any array would look like this:

Array:
- [0] value
- [1] value
- [2] value
- ..
- [N] value
- [IndexOf] value

To avoid the non-wanted inherited methods and properties you can use the method hasOwnProperty():

for (j in j){
    if(i.hasOwnProperty(j){
        alert(i[j])
    }
}

hasOwnProperty checks if the key is not inherited and belongs to the actual object. This way only the needed values pass through.

This happens because in IE, since the method doesn't exist, then it is added to the Array.prototype, and it remains being enumerable.

For woking with Arrays (and generally any array-like object), I don't recommend the use of the for...in statement.

Why ?

  • The for...in statement is meant to enumerate object properties.
  • The for...in statement crawls up the prototype chain as you noticed.
  • The order of iteration can be arbitrary, iterating over an array may not visit the elements in the numeric order.

The most simple approach, the plain for loop:

for (var j = 0; j < i.length; j++) {
    alert(i[j]);
}

See also:

Can you try adding:

for (j in i) {
    if (i.hasOwnProperty(j)) { 
        alert(j); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!