For example:
There is such a piece of code:
var array = [];
array.push(1);
array.push(2);
array.push(3);
for(var i in array) {
console.log(i ":" array[i]);
}
What will be output at this time? Of course it is 0:1 1:2 2:3
But if you add Array.prototype.say = "hello";
before for in, what will be output when you run it again?
0:1 1:2 2:3 say:hello
See, at this time, it will output the properties of the prototype
In many cases, we don’t need to traverse the properties of its prototype. Another reason is that the object we are using now ,We cannot guarantee that other developers have ,added some attributes to its prototype? So, let’s filter the properties of our object. This time we use the hasOwnProperty method, as follows:
for(var i in array){
if(array.hasOwnProperty(i)) {
console.log(i ":" array[i]);
}
}
Think about it again, what will be output now? Of course it's 0:1 1:2 2:3.