Shallow copy and deep copy

1.JavaScript data types (8)

Value types: String, Number, Boolean, Null, Undefined, Symbol, Bigint.

Reference data types: Object, Array, Function.

2. Copy (object reference)

       

Here we create a new object with two attributes, one name and the other age, which is stored in the QZC variable — copy the QZC variable to get a new object ZCW and modify the NAME attribute of ZCW.

Expected results:

       

Actual results:

       

The name attribute of ZCW is changed only, but the name attribute of QZC and ZCW is changed simultaneously. This is because when ZCW copies QZC (reference data type), it copies a pointer to the same object stored in heap memory, so when ZCW is used to manipulate objects in heap memory, QZC changes as well.

3. Shallow copy (copy the parent object, not the internal child object of the object.)

To solve the problem of modifying ZCW objects, QZC will also change. We copy the QZC objects using object.assign ().

       

Results obtained:

       

Common shallow copy methods:

Object.assign()const ZCW = object.assign ({}, QZC), extension operator const ZCW = {… qzc}

Shallow copy may cause problems:

       

Here we create a new object with two attributes, one with a key name of name and the other with a key name of children. This object is stored in the QZC variable — shallowly copy the QZC variable to get a new object, ZCW, and modify the children name attribute of ZCW.

Expected results:

       

Actual results:

       

QZC; ZCW; children; ZCW; This is because when ZCW shallow copies QZC, it does not copy the internal child objects of the object.

4. Deep copy (full copy of parent object and child object)

Parse (json.stringify ()) to solve the problem of modifying the children name attribute of ZCW while changing the children name attribute of QZC and ZCW, we copied the QZC object using json.parse (json.stringify ()).

       

Results obtained:

       

Common deep copy methods:

Parse (json.stringify ())

5. Application of deep copy in projects

       

When providing form data to the background, it is often necessary to do some processing on the data in the submitted object, and even change the data type. For example, submitParams is the data that the user has filled out to submit, and the insureType attribute is the box group used to bind ElementUI. It must be an array according to ElementUI’s specification. If we simply converted submitParams’ insureType property to a string, the page would be cluttered. Parse (json.stringify ())) to make a deep copy of the params object, and convert the data in params to the background as required.

Object.assign(

1. Grammar:

Object.assign(target, ... sources)Copy the code

Parameters:

target

The target object

sources

The source object

2. Usage:

The object.assign () method is used to assign the values of all enumerable properties from one or more source objects to target objects. It will return the target object.

        

The results obtained

        

3. Description:

If an attribute in the target object has the same key, the attribute is overwritten by an attribute in the source object. Properties of subsequent source objects similarly override properties of previous source objects.

       

Results obtained:

       

4. Use of Object.assign() in Vue projects

Sometimes you may need to assign multiple new properties to existing objects, such as object.assign () or _.extend(). However, new properties that are thus added to the object do not trigger updates. In this case, you should create a new object with the property of the original object and the property of the object to be mixed in.

// Replace 'object.assign (this.someObject, {a: 1, b: 2})' this.someObject = object.assign ({}, this.someobject, {a: 1, b: 2}) 'this.someobject = object.assign ({}, this.someobject, {a: 1, b: 2}) 2})Copy the code

      

Vue. Set (target, propertyName/index, value)

1. Problems that may be encountered during project development

Code:

        

Expected results:

     

Actual results:

      

Solution:

       

Results obtained:

    

2. Why is this a problem

Because the Vue cannot detect common new property (such as this. MyObject. NewProperty = ‘hi’)

3. Why does vue.set solve this problem

Because vue.set can add a property to a reactive object and make sure that the new property is also reactive and triggers view updates. It must be used to add a new property to a reactive object.

export function set (target: Array<any> | Object, key: any, val: any): any { if (process.env.NODE_ENV ! = = 'production' && (isUndef (target) | | isPrimitive (target))) {/ / if the first parameter is the undefined or null in non-production environments will print the warning information. warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: Any)} ')} if (array.isarray (target) &&isvalidarrayindex (key)) {// if the target isArray and index is a valid value target.length = Math.max(target. Length, key) target. Splice (key, 1, val) return val} if (key in target &&! (key in object.prototype) {// Target [key] = val Const ob = (target: any).__ob__ /** * _isVue: The Vue object has the _isVue attribute, that is, it is not allowed to add attributes to the Vue sample object. * does not allow the Vue. Set / $set function as root data object to add attributes (vm) $data) * / if (target) _isVue | | (ob && ob. VmCount)) {process. The env. NODE_ENV! == 'production' && warn('Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ) return val } if (! Ob) {// Target itself is not responsive data, DefineReactive (ob.value, key, val) ob.dep.notify() return val} defineReactive(ob.value, key, val) ob.dep.notify() return val}Copy the code

Lessons to learn:

What is the change method?

Change method:

Changing methods, as the name suggests, changes the original array from which they were called.

Common change methods:

Splice (), push ()

Use of change methods in projects:

Arr = arr.splice(2, 1) // Unnecessary writing arr.splice(2, 1) // Correct writingCopy the code

Non-changing methods:

They do not alter the original array, but always return a new one.

Common non-change methods:

Filter (), 丶 (), 丶 (), 丶 ()

Use of non-change methods in projects:

Concat (arr2) // Arr3 = arr.concat(arr2) // Arr3 is the concatenated array of arR and ARR2Copy the code

Return as early as possible to reduce nesting of if and else

If, else nesting:

      

Return as soon as possible

      

Fourth, Async/Await

1. Simpler code

During the execution of async function, if an await is encountered, the execution will be suspended. After the triggered asynchronous operation is completed, the execution of async function will be resumed and the parsing value will be returned.

The await operator is used to wait for a Promise object and can only be used inside the async function.

// good
function getTableData() {
  api.getTableData().then(res => {
    console.log(res)
  })
 }

// better
async function getTableData() {
  const res = await api.getTableData()
  console.log(res)
}
Copy the code

2. If only the outer function is async, an await written inside the inner function will report a syntax error.

      

Because async is a type of function, each one has to be written, not written. This does not mean that an async function is defined within an async function

Correct way to write it:

       

3. Error handling

// good
function getTableData() {
  api.getTableData().then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err)
  })
}

// better
async function getTableData() {
  try {
   const res = await api.getTableData()
   console.log(res)
  } catch(err) {
    console.log(err)
  }
}
Copy the code