Object definition
An unordered collection of data, a collection of key-value pairs declared object:
let obj = {'name':'frank'.'age':18}
let obj = new Object({'name':'frank'})
console.log({'name':'frank'.'age':18})
Copy the code
A few details: The key name is a string, not an identifier, it can contain any character and the quotation marks can be omitted, but only the identifier can be written after it is omitted and the key name is still a string
How do I use variables for attribute names
let p1 = 'name'
let obj = {[p1]:'frank'}
Copy the code
If the value is not a string, it is automatically converted to a string. If the value is not a string, it is automatically converted to a string
Object’s hidden properties and stereotypes
JS each object has a hidden attribute, the hidden attribute to store the Shared attributes of the object’s address, the common attributes of objects called prototype, that is to say, the hidden attribute with the address of the prototype Every object has a prototype, the prototype in the Shared attributes of the object, the object’s prototype is object, So the prototype of an object has a prototype and the prototype of obj={} is the prototype of all objects, and that prototype contains properties common to all objects, which is the root of the object, and that prototype also has a prototype, which is null
Add, delete, change and check objects
Deleting object Properties
delete obj.xxx
delete obj['xxx']
Copy the code
‘XXX ‘in obj === false :’ XXX ‘in obj && obj. XXX === undefined
View the properties
Keys (obj) View itself + common property console.dir(obj) or print obj.__proto__ with object.keys to determine if a property is own or shared obj.hasownProperty (‘toString’)
View the properties
Parenthesis syntax: obj[‘keys’] dot syntax: obj.key
Modify or add attributes
Direct assignment
let obj = {name : 'frank'}// Name is a string
obj.name = 'frank'// Name is a string
obj['name'] = 'frank'
let key = 'name'; obj[key] ='frank'
let key = 'name'; obj.key ='frank'// error, obj. Key = obj['key']
Copy the code
Batch assignment
Object.assign(obj,{age:18,gender:'man'})
Modify or add a common property
Common attributes cannot be modified or added by themselves. To forcibly modify or add attributes on the stereotype
obj.__proto__.toString = 'xxx'// __proto__ is not recommended
Object.prototype.toString='xxx'
Copy the code
In general, not modifying a prototype can cause a lot of problems. Object.creat() is recommended.
Key in obj and obj.hasOwnProperty(‘toString’
Obj. HasOwnProperty (‘key’) can determine whether the property is owned or shared