When you use the for in loop, you return all the enumerable properties that are accessible through the object, both in the instance and in the stereotype.

(1) No attribute added to Object.prototype

var obj={"name":"wjy","age":26,"sex":"female"}; Var keys=[]; // Define an array to accept key var values=[]; // Define an array to accept value for(var key in obj){keys.push(key); values.push(obj[key]); // Get value console.log(eval("obj."+key)); } console.log(obj.name); //wjy console.log("keys is: "+keys+" and values is: "+values); //keys is : name,age,sex and values is : wjy,26,femaleCopy the code

When you loop through the properties of an Object with a for in loop, all properties on the prototype chain will be accessed. For example, if we add a bar property to Object.prototype, the for in loop will loop out the bar property:

Object.prototype.bar = 10; / / modify the Object. The prototype var obj = {" name ":" wjy ", "age" : 26, "sex", "female"}; Var keys=[]; // Define an array to accept key var values=[]; // Define an array to accept value for(var key in obj){keys.push(key); values.push(obj[key]); } console.log("keys is: "+keys+" and values is: "+values); //keys is : name,age,sex,bar and values is : wjy,26,female,10Copy the code

It is recommended to always use the hasOwnProperty method. This will avoid interference caused by the extension of the prototype object:

function allpro(obj){ var keys=[]; var values=[]; For (var key in obj){// Only the attributes of the object are iterated, not the attributes inherited from the prototype chain. if (obj.hasOwnProperty(key) === true){ keys.push(key); values.push(obj[key]); }} console.log("keys is: "+keys+" and values is: "+values); } Object.prototype.bar = 1; / / modify the Object. The prototype var o = {" name ":" wjy ", "age" : 26, "sex", "female"}; // Define an object object allpro(o); //keys is : name,age,sex and values is: wjy,26,femaleCopy the code