Example of using hasownproperty in js
In js, we may often use for in to traverse the attributes of objects. Of course, the attributes obtained in for in can only be enumeration attributes, it will traverse the attributes of the object (including the attributes of the prototype). You can see the example at the bottom of the page.
For 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?
Copy the Code 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:
Copy the Code 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.