A statement object
let obj = { 'name': 'frank', 'age': 18 }
let obj = new Object({'name': 'frank'})
console.log({ 'name': 'frank', 'age': 18 })
The key name is a string, not an identifier, and can contain any character. Quotation marks can be omitted, and only identifiers can be written after the omission. Keys (obj) can be used to obtain all keys of obj
Results obtained without quotation marks may not be as expected
let obj = {
1: 'a'.3.2: 'b'.1e2: true.1e-2: true.234.: true.0xFF: true
};
Copy the code
Object. Keys (obj) will get [” 1 “, “100”, “255”, “3.2”, “0.01”, “0.234”]
Variable and attribute names
Key is the attribute name of the object and value is the attribute value of the object
let p1 = 'name'
let obj = { p1 : 'frank'} // Write it like this, property name is 'p1'
let obj = { [p1] : 'frank' } // The property name is 'name'
Copy the code
Attribute names without [] are automatically changed to strings, and attribute names with [] are evaluated as variables
var obj = {
[1+2+3+4] :"10";
}
// keys(obj) get ["10"]
Copy the code
Let a = symbol (); let obj = { [a]: ‘Hello’ };
Delete the properties
delete obj.xxx;
或delete obj['xxx'];
Delete XXX from objattributeThe XXX attribute is not in objobj.xxx === undefined;
Delete obj from XXXAttribute values- available
'xxx' in obj;
To confirm this fact
Read properties (view all properties)
- View all of its properties
Object.keys(obj);
Object.values(obj);
Check its own value,Object.entries(obj);
View their own key-value pairs - View self + Common properties
console.dir(obj);
Direct printing:obj.__proto__;
(The hidden attribute has no specified name, so the latter method is not recommended) - Determine whether the attribute is self-contained or common
obj.hasOwnProperty('toString');
View the properties
obj['key'];
This is recommended because the dot syntax can trick people into thinking key is not a stringobj.key;
- Cheat grammar:
obj[key];
The value of the key variable is usually not ‘key’.
Write attributes (modify or add attributes)
let obj = {name: 'frank'}; // Name is a string
obj.name = 'frank'; // Name is a string
obj['name'] = 'frank';
obj['na'+'me'] = 'frank';
let key = 'name'; obj[key] = 'frank';
- Batch assignment
Object.assign(obj, {age: 18, gender: 'man'});
- Modify or add a common property
- Common attributes cannot be modified or added by themselves
Let obj = {}, obj2 = {} // toString;
obj.toString = 'xxx'; // Only obj attributes will be changed
obj2.toString; // The toString of the prototype
- Modify or Add attributes to the prototype In general, do not modify the prototype, it can cause a lot of problems
-
obj.__proto__.toString = 'xxx' ; // __proto__ is not recommended
-
Object.prototype.toString = 'xxx';
-
let common = {kind: 'human'}; let obj = Object.create(common); obj.name = 'frank'; let obj2 = Object.create(common); obj2.name = 'jack'; Copy the code
Declare obj and obj2 with common as the prototype
-
- Common attributes cannot be modified or added by themselves