We may often use forin in js to traverse attributes in objects. Of course, the attributes obtained in forin can only be enumeration attributes, it will traverse the attributes of the object (including the attributes of the prototype). You can see the following example:
There is such a piece of code:
The Code 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 is
However, if Array. prototype. say = "hello" is added before for in ";
What will be output when I run it again?
The Code is as follows:
Say: hello
See it. At this time, it will output the properties of the prototype.
In many cases, we do not need to traverse the properties of the prototype. Another reason is that the objects we currently use cannot be guaranteed. Do other developers have them, what about adding some attributes to its prototype? So, let's filter out the attributes of our object. At this time, the hasOwnProperty method is used as follows:
The Code is as follows:
For (var I in array ){
If (array. hasOwnProperty (I )){
Console. log (I + ":" + array [I]);
}
}
What will be output now? Of course it is.