For example:
There is a piece of code like this:
The code copy is as follows:
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's 0:1 1:2 2:3
But if you add Array.prototype.say = "hello" before for in;
What will output when running again?
The code copy is as follows:
0:1 1:2 2:3 says:hello
See, at this time, it will output the properties of the prototype
In many cases, we do not need to traverse the properties of its prototype. Another reason is that we cannot guarantee that the objects we are using now, do other developers have any properties to add some properties to its prototype? So, let's filter the properties of our object. At this time, we use the hasOwnProperty method, as follows:
The code copy is as follows:
for(var i in array){
if(array.hasOwnProperty(i)) {
console.log(i+":"+array[i]);
}
}
Think about what will be output now? Of course it is 0:1 1:2 2:3.