//someone might extend funny methods from the global object
Object.prototype.hello = function() {
return "hello";
};
//your code trying to count the number of properties or do something for your application
var object = {x: 5, y: 10};
var i = 0;
for(var property in object) {
i++;
}
alert(i); // 3, you expect only 2 why it has three?
To solve this above problem, use hasOwnProperty("property") anywhere when you use for-in loop. hasOwnProperty() returns whether the pass-in property is inherited property or not.
var i = 0;
for(var property in object) {
if(object.hasOwnProperty(property))
i++;
}
alert(i); // 2, this is what expected
No comments:
Post a Comment