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
/ in
loops 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 for
loop instead.
Javascript's for
/ in
loop is not intended to loop over arrays.
That's javascript's normal functionality. the for .. in
loop gets all of an object's keys because it is meant for looping over an object, not an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With