I added a method trigger
to the prototype of Object:
Object.prototype.trigger = function() {
// ...
return this;
};
And then have a "for in" loop:
var obj = { 4: 15, 10 : 41, 11 : 46, 12 : 51, 20 : 74 }
for( item in obj ) {
foo( obj[item] );
}
But this loop has 6 iterations instead of 5. The last iteration is with key:
item = "trigger"
Why is the loop iterating over the __proto__
part of the object?
for...in
goes over all of the object properties without distinguishing between properties on the object itself or any of its ancestors.
In order to go over only properties defined on the object itself, you can use Object.prototype.hasOwnProperty
:
const obj = { 4: 15, 10 : 41, 11 : 46, 12 : 51, 20 : 74 }
for( item in obj ) {
if(obj.hasOwnProperty(item) {
foo( obj[item] );
}
}
// will ignore the trigger func and everything else defined on any prototype
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