According to the way to add indexOf method to Array class in IE6, how do I now reject this method from iterating through any random array? For example:
Array.prototype.indexOf = function(needle) { ... };
var array = [1, 2, 3];
for (var i in array) {
document.write(i + ': ' + array[i]);
}
gives output
0: 1
1: 2
2: 3
indexOf: function ...
How can I skip indexOf property and stop iterating on it without adding any code to where
for(...)
is called?
This is a well known issue with Javascript’s
for..inloops.You may think you’re just looping through the elements of an array or an object that you’ve added directly, but it will also loop through any methods in the prototype as well. This can have unexpected consequences.
There are two ways around it:
Firstly, for arrays, don’t use
for..in. Use a simplefor()loop instead — ie:This form is recommended for arrays, because it is guaranteed to only iterate through the numeric array elements.
It doesn’t work for generic objects, of course, since they don’t have a
lengthproperty nor numeric elements. For these, you still need to usefor..in, but you should also always include anif()statement inside afor..inloop to filter out unwanted elements.The format of this should look like this:
This looks ugly, but because of the problems of not doing it, it is recommended best-practice for Javascript, to the point that JS code quality cheking tools such as JSLint and JSHint will flag it up as a problem if you don’t write your
for..inloops like this.You can read more about this problem here: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/