Two syntax for declaring objects
1.let obj = {‘name’: ‘jiangjiang’, ‘age’:18}
Obj is the object name. Object name does not have to be obj.
2.let obj = new Object({‘name’: ‘jiangjiang’, ‘age’: 21})
The most correct way to write! But usually not
Let Object name =new Object({‘ keyname ‘:’ keyvalue ‘,… . })
The key name can contain any character, and the quotation marks for ‘key name’ can be omitted, but it is best not to omit them to avoid errors.
Note: key names are strings with or without quotes!!
Object.keys(obj) can obtain all the key names (attribute names) of an Object named obj!
How do I delete an object’s attributes
Methods 1. Delete obj. XXX
Methods 2. Delete the obj [‘ XXX ‘]
How do I view the properties of an object
-
View all of your own properties: Object.keys(obj)
-
View the + common property: console.dir(obj) or print obj._ _ proto_ _ with object. keys
-
How to tell if a property is own or shared: obj.hasownProperty (‘XXX’)
How do I modify or add attributes to an object
- Modify the
Alter self attribute
[‘name’]=’ hippo ‘
Batch modify attribute values of attributes:
Object.assign(obj,{‘age’:18,… })
Modify common properties: You cannot modify or add common properties by yourself. Common properties are only readable and cannot be changed
let obj = {name: 'Tom'};
Object.prototype['toString']='xxx';
obj.toString //'xxx'
Copy the code
Let obj = object.create (common) Object.create(common
Let common = {hairColor: 'black', country: 'China '}; let obj = Object.create(common); Obj. Name = 'zhang3 '; let obj2 = Object.create(common); Obj2. name = 'obj2 '; Object.assign(obj2, {age: 18, city: 'Shanghai '}); console.log(obj.country); // "guangzhou" console.log(obj2.country); // ""Copy the code
Obj. hasOwnProperty(‘name’)
The difference is between own properties and shared properties, when we view and delete
That is, the search will find the prototype of obj, but if you modify or add the name attribute does not change the prototype of the property
Let obj = {name:'xiaoxiao', age:18} let obj = {name:'xiaoxiao', age:18} Obj. HasOwnProperty ('name') The answer is trueCopy the code
A subject that must be understood
let list = ['name', 'age', 'gender']
let person = {
name:'frank', age:18, gender:'man'}
for(let i = 0; i < list.length; i++){
let name = list[i]
console.log(person__???__)
}
Copy the code
Causes all the attributes of Person to be printed
Options:
console.log(person.name)
console.log(person[name])
prompt
The name of option 1 is a string, and the name of option 2 is a variable
Let name = ‘frank’ obj[name] is equivalent to obj[‘frank’] instead of obj[‘name’] and obj.name