Two syntax for declaring objects
writing
let obj = { ‘name’: ‘frank’, ‘age’: 18 }
let obj = new Object({‘name’: ‘frank’})
console.log({‘name’: ‘frank, ‘age’: 18 })
details
- Key names are strings, not identifiers, and can contain any character
- Quotation marks can be omitted, after which only identifiers can be written
- Even if quotes are omitted, the key is still a string (important)
How do I delete an object’s attributes
Delete obj. XXX or delete obj[‘ XXX ‘]
- Delete the XXX property of obj
- Please distinguish between “attribute value undefined” and “without attribute name”.
Contains no attribute name
- ‘xxx’ in obj === false
Contains the attribute name, but the value is undefined
- ‘xxx’ in obj && obj.xxx === undefined
Note that obj. XXX = = = is undefined
- Cannot determine whether ‘XXX’ is a property of obj
analogy
- Do you have any toilet paper?
- A: No // no attribute name
- B: Yes, but not with // attribute name, but with undefined value
How do I view the properties of an object
There are two ways to view properties
- Parenthesis syntax: obj[‘key’]
- Point syntax: obj.key
- Obj [key] // The value of the variable key is not ‘key’.
Use bracket syntax in preference
- The dot syntax will trick you into thinking that key is not a string
- When you’re sure you don’t confuse the two grammars, switch to grammar
How do I modify or add attributes to an object
Direct assignment
Let obj = {name: ‘frank’} // name is a string
Obj. name = ‘frank’ // name is a string
obj[‘name’] = ‘frank’
Obj [name]= ‘frank’ //
obj[‘na’+’me’] = ‘frank’
let key = ‘name’; obj[key] = ‘frank’
let key = ‘name’; Obj. key = ‘frank’ // false
Because obj. Key is equivalent to obj[‘key’]
Batch assignment
Object.assign(obj, {age: 18, gender: ‘man’})
Modify or add a common property
Modify or add common attributes by itself
- Let obj = {}, obj2 = {} // toString
- Obj. ToString = ‘XXX’ will only change the obj property
- Obj2.tostring is still a prototype
I want to change or add attributes to the prototype
- Obj.proto. toString = ‘XXX’ // proto is not recommended
- Object.prototype.toString = ‘xxx’
- In general, don’t modify a prototype, it can cause a lot of problems
Modifying hidden attributes
Not recommendedproto
let obj = {name:’frank’}
let obj2 = {name: ‘jack’}
let common = {kind: ‘human’}
obj.proto = common
obj2.proto = common
Object. Create is recommended
let obj = Object.create(common)
obj.name = ‘frank’
let obj2 = Object.create(common)
obj2.name = ‘jack’
Norms basically mean, if you want to change, change at the beginning, don’t change later
Obj. hasOwnProperty(‘name’)
‘name’ in obj indicates whether an obj object has a name attribute
HasOwnProperty (‘name’) is a property that indicates whether the name in obj is its own