A New Understanding on navigating the object attributes, how to traverse only the object's own properties

 

key and value value usually want to generally be applied for / in statement while traversing an object, you can quickly get the object through the for / in statement

var obj = {name:'zhang',age:24};
for(var key in obj){
    console.log(key);  //name age
    console.log(obj[key]);  //zhang 24
}
However, when using the for in loop through the object's properties, all properties on the prototype chain will be accessed:
function Pro (name, Age) {
     the this .name = name;
     the this .age = Age; 
 } 
Pro.prototype.hobby = 'badminton' ; 
Pro.prototype.qq = '123' ;
 var Pro1 = new new Pro ( 'WAN' , 24 ); 
the console.log (Pro1); 
for ( var P in Pro1) { 
    the console.log (P);   // prints all attributes comprising chain prototype 
}
However, if you want to traverse the object itself only attribute it, and today just to see this, I suddenly thought up, you can use object properties to do a screening hasOwnProperty
for ( var P in Pro1) {
     IF (pro1.hasOwnProperty (P)) { 
    the console.log (P);   // this print attribute contains just the object's own 
    } 
}

Guess you like

Origin www.cnblogs.com/home-/p/11916837.html