I have created a JavaScript extension for an array object as follows:
Array.prototype.where = function (lamda) {
var results = [];
for (var i in this) {
if (lamda(this[i])) {
results.push(this[i]);
}
}
return results;
}
When I iterate through the array using a for loop like:
var myArray = [1,2,3,4];
for(var i in myArray){
alert(myArray[i]);
}
…my extensions are enumerated as well.
Any ideas?
This behavior is by design.
for/inloops iterate over every property in an object, including those inherited from prototypes.You can check
if (myArray.hasOwnProperty(i))to skip inherited properties.However, you should use a regular
forloop instead.Javascript’s
for/inloop is not intended to loop over arrays.