There are seven data types in JS: number, string, bool, symbol, undefined, NULL, object

The object object is the only complex type, while the other six types are all simple types.

Object syntax

An object is a set of key-value pairs. It is an unordered set of compound data. It is written as follows:

let obj = {'name': 'jack'.'age': 18}    // Simple
let obj = new Object({'name': 'jack'})   // Standard notation
console.log({'name': 'jack'.'age': 18}) // Anonymous object
Copy the code

Property name: Each key is the property name of the object

Property values: Each value is the property value of the object.

A few details about the key name:

  • The key name is a string, not an identifier, and can contain any character (including “, “, “, number, Chinese, emoji, etc.).

  • If the key name does not meet the conditions of the identifier and is not a number, the quotation marks must be placed. Otherwise, an error will be reported.

  • Even if the quotes are omitted, the key name is still a string. (Important)

let obj1 = {
  ' ': 1.' ': 2.'Chinese': 3.'😀': 4.'77name': 'jack'
}

let obj2 = { 1: 111 }  // There is no numeric subscript, and the key name is only a string
Object.keys(obj2)      // Get all keys of obj2: ["1"]
Copy the code

A notable example:

{ foo: 'a' }    // "a" can be verified in Firefox
Copy the code

Foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo

Strange property names

In JavaScript, all property names are automatically converted to strings

let obj = {
    1: 'a'.3.2: 'b'.1e2: true.// Change 1e2 to the number 100, then to '100'
    1e-2: true.234.: true.0xFF: true   // Hexadecimal, automatically converted to the number 255, and then "255"
};

obj;
// Object {
// 1: "a",
/ / 3.2: "b",
// 100: true,
/ / 0.01: true,
/ / 0.234: true,
// 255: true
// }

Object.keys(obj);  //["1", "3.2", "100", "0.01", "0.234", "255"]
Copy the code

The variable is the attribute name

Using variables as attribute names: [variable name]: value

Attribute names without [] are automatically changed to strings. Attribute names with [] are evaluated as variables, and values that are not strings are automatically changed to strings.

let p1 = 'name'
let obj = { p1: 'jack' }   // write this, attribute name 'p1'
let obj = { [p1]: 'jack' } // the attribute name is 'name'
Copy the code

Add, delete, modify and check the object

Deletes the properties of an object

The delete operator is used to delete a property of an object. Use delete obj. XXX or delete obj[‘ XXX ‘] to delete the XXX attribute of obj. Return true on successful deletion.

let obj = { name: 'jack'.age: 18 }

obj.name = undefined
obj    // {name: undefined, age: 18}, delete attribute 'jack'

delete obj.name    // true
obj    // {age: 18}

delete obj['name'] // delete a property that does not exist. Delete does not report an error and returns true
Copy the code

Be careful to distinguish between the attribute value being undefined and not containing the attribute name.

Nothing means nothing, undefined means undefined, can’t be vague.

Property exists: in operator

The in operator checks whether an object contains a property (the key name, not the key value), returning true if it does, false otherwise.

let obj = { age: 18 }
'name' in obj  False, name is not the property name of obj
'age' in obj   //true, age is the property name of obj
Copy the code

Attribute name = undefined; attribute name = undefined;

'xxx' in obj && obj.xxx === undefined
Copy the code

Note that obj. XXX === undefined cannot determine whether ‘XXX’ is an attribute of obj, but use in to judge.

let obj1 = {}
let obj2 = { x: undefined }
obj1.x === undefined  //true
obj2.x === undefined //true
'x' in obj   //false
'x' in obj2  //true
Copy the code

View the properties of the object (read properties)

1. View all its propertiesObject.keys(obj)

2. View itself + Common propertiesconsole.dir(obj)

3. Determine whether an attribute is self-contained or sharedobj.hasOwnProperty('toString')

let obj = { name: 'jack'.age: 18 }

Object.keys(obj)    //["name", "age"]
Object.values(obj)  //["jack", 18]
Object.entries(obj) // Check the key and value

console.dir(obj)    // Prints all self and common properties as a directory

'toString' in obj  // True, the use of in does not distinguish whether an attribute is self-contained or common
obj.hasOwnProperty('toString') //false, indicating that toString is a common attribute
obj.hasOwnProperty('name')     //true, indicating that name is its own attribute
Copy the code

4. View a property

  • Brackets syntax obj[‘key’] (preferred)
  • Some grammarobj.key
  • Obj [key] obj[key] obj[key] obj[key]
let obj = {name: 'jack'.age: 18 }

obj['name']       //"jack"
obj.name          //"jack"
obj['na' + 'me']  //"jack"

obj[name]           // The value of name is undefined
name                //"", the value of name is"
window.name = 'age' // Set name to 'age'
obj[name]           / / 18

obj[console.log('name')] //undefined
Copy the code

In the above code, the value of the console.log(‘name’) expression is undefined.

Obj [console.log(‘name’)] is equivalent to obj[‘ name’], but obj does not have undefined.

4. Name [name]

About the obj. Name

  • Obj [‘name’]

  • Name = obj[name]

  • The name here is a string, not a variable.

About the obj [name]

  • let name='jack'

  • Obj [name] = obj[‘jack’]

  • Instead of obj[‘name’] and obj.name

  • The name here is the variable

Questions to think about:

let list = ['name'.'age'.'gender']
let person = {
  name: 'jack'.age: 18.gender: 'man'
}
for (let i = 0; i < list.length; i++) {
  let name = list[i]
  console.log(person__???__)
}
Copy the code

How should the console statement in the above code be filled in so that all of the properties of person are printed?

Option 1: console.log(person[name]) Option 2: console.log(person[name])

Modify or add an object property (write property)

Modify or add own attributes

1. Direct assignment

let obj = { name: 'jack' }

obj.age = 18
obj.name = 'tom' // Name is a string
obj['name'] = 'tom'
obj['na' + 'me'] = 'tom'
Obj [name] = 'Tom' obj[name] = 'Tom' obj[name] = 'Tom'

let key = 'name'
obj[key] = 'tom'
Obj ['key'] obj['key']
Copy the code

2. Batch assignmentObject.assign(NEW API for ES 6)

Object.assign(obj, { p1: 1.p2: 2.p3:3.p4: 4.p5: 5})
obj  //{name: "tom", age: 18, p1: 1, p2: 2, p3: 3, p4: 4, p5: 5}
Copy the code

Modify or add common attributes

  1. Common properties cannot be modified or added by themselves
let obj1 = {}, obj2 = {} / / the toString
obj1.toString = 'xxx'    // We are only changing obj1's own properties
obj2.toString            // Still on the prototype
Copy the code
  1. If you want to modify or add attributes to the stereotype
obj.__proto__.toString = 'xxx' // Not recommended to use __proto__ because it affects performance
Object.prototype.toString = 'xxx'
Copy the code

In general, do not modify the prototype, it will cause a lot of problems.

Modifying hidden properties

  1. Not recommended__proto__
let obj = { name: 'jack' }
let obj2 = { name: 'tom' }
let common = { kind: 'human'}
obj.__proto__ = common
obj2.__proto__ = common
Copy the code
  1. It is recommended to useObject.create
let common = { kind: 'human' }
let obj = Object.create(common) // Create obj with common as prototype
obj.name = 'jack'
let obj2 = Object.create(common) // Create obj2 with common as the prototype
obj2.name = 'tom'
Copy the code

In general, do not modify the prototype, it will cause a lot of problems.

HasOwnProperty (‘ XXX ‘) in obj

‘xxx’ in obj

The in operator is used to determine whether object obj contains the XXX attribute, but does not distinguish whether the attribute XXX is self-contained or inherited from the prototype chain.

obj.hasOwnProperty(‘xxx’)

Obj.hasownproperty (‘ XXX ‘) Specifies whether object obj has the XXX property in its own property.

  • returntrue,xxx 是 objSelf attribute of
  • returnfalse,xxx 是 objInherited properties (common properties) of.
let obj = { name: 'jack'.age: 18 }
'name' in obj      //true
'toString' in obj  //true
obj.hasOwnProperty('name')      // True, name is its own attribute
obj.hasOwnProperty('toString')  // False, toString is an inherited property
Copy the code