Shallow copy

Shallow copy refers to the creation of new data that has an exact copy of the original data attribute values. If the property is of a primitive type, the value of the primitive type is copied. If the attribute is a reference type, the memory address is copied.

In JS, shallow copy methods have the following:

Object.assign

var obj={
    age:18,
    names:{
      name1:'lixi',
      name2:'xixi'
   },
   hobby:['sing','shopping']
}
var newObj = Object.assign({},fxObj)
Copy the code

slice()

  const fxArr = ['One','Two','Three']
  const fxArrs = fxArr.slice(0)
  fxArrs[1] = 'love'
  console.log(fxArr)  // ['One','Two','Three']
  console.log(fxArrs)  //['One','love','Three']
Copy the code

concat()

  const fxArr = ['One','Two','Three']
  const fxArrs = fxArr.concat()
  fxArrs[1] = 'love';
  console.log(fxArr) // ['One', 'Two', 'Three']
  console.log(fxArrs) // ['One', 'love', 'Three']
Copy the code

Extended operator

    const fxArr = ["One", "Two", "Three"]
    const fxArrs = [...fxArr]
    fxArrs[1] = "love";
    console.log(fxArr) // ["One", "Two", "Three"]
    console.log(fxArrs) // ["One", "love", "Three"]
Copy the code

Deep copy

Deep copy opens up a new stack, two objects have exactly the same properties, but correspond to different addresses, modify the properties of one object, the properties of the other object does not change.

Common deep-copy methods are as follows:

_.cloneDeep()

const _ = require('lodash'); const obj1 = { a: 1, b: { f: { g: 1 } }, c: [1, 2, 3] }; const obj2 = _.cloneDeep(obj1); console.log(obj1.b.f === obj2.b.f); // falseCopy the code

jQuery.extend()

const $ = require('lodash'); const obj1 = { a: 1, b: { f: { g: 1 } }, c: [1, 2, 3] }; const obj2 =$.extend(true, {}, obj1); console.log(obj1.b.f === obj2.b.f); // falseCopy the code

JSON.stringify()

const obj2=JSON.parse(JSON.stringify(obj1));
Copy the code
  • This method, however, ignores undefined, symbol, and functions
    const obj = {
        name: 'A',
        name1: undefined,
        name3: function() {},
        name4:  Symbol('A')
    }
    const obj2 = JSON.parse(JSON.stringify(obj));
    console.log(obj2); // {name: "A"}
Copy the code