This is the 8th day of my participation in Gwen Challenge
The way an object can be traversed with enumerable properties
for in
When a for in loop iterates through an object’s properties, all enumerable properties on the stereotype chain are accessed.
Object.prototype.name="lf";
let person ={ age: 18 };
for (var key in person) {
console.log(key, person[key]);
}
//age:18
//name:lf
//hasOwnProperty traverses only properties of the object itself, not properties inherited from the prototype chain. You can use the hasOwnProperty method to filter.
Object.prototype.name="lf";
let person ={ age: 18 };
for (var key in person) {
if(person.hasOwnProperty(key)){
console.log(key, person[key]); }}//age:18
Copy the code
Object.keys()
The object.keys () method returns an array of the given Object’s own enumerable properties
Object.prototype.name="lf";
let person ={ age: 18 };
let list = Object.keys(person)
//["age"]
Copy the code
You can use object.keys (person).length to obtain the number of attributes of an Object
JSON.stringify()
Object.prototype.name="lf";
let person ={ age: 18 };
let list = JSON.stringify(person)
//"{ "age" : 18 }"
Copy the code
Defining object properties
Object.defineProperty(obj, prop, desc)
There are two types of data descriptor and access descriptor, and they cannot be mixed.
Data descriptor
let person = {}
Object.defineProperty(person, "name", {
value: "lf".enumerable: true.writable:true
});
Copy the code
Access descriptor form
let Person = {}
Object.defineProperty(Person, 'name', {
get: function () {
return this.value
},
set: function (newVal) {
this.value = newVal
},
configrable:true.enumerable:true
})
Copy the code
Other methods on attributes
Object.preventExtensions()
Disallows an object to add new attributes and keep existing attributes.
Object.seal()
Sealed object, equivalent to Object.preventExtensions (…) + configurable: false.
Object.freeze()
Freeze object, equivalent to Object.preventExtensions (…) + 64x :false + writable: false
Object.defineProperties()
Batch customize object properties.
var obj = {}
Object.defineProperties(obj, {
name: {
value: ‘John‘,
writable: true
},
age: {
value: 30.enmuerable: true}})Copy the code
Object.getOwnPropertyDescriptor()
Returns a descriptor for a property of this object.
var obj = {}
ObjectDefineProperty (obj, "name", {value: ‘Backus‘,
writable: true.enumerable: true
})
var des = Object. GetOwnPropertyDescriptor (obj, 'name')console.log(des)
Copy the code