The commonplace of JS deep copy and shallow copy



We often see the terms “deep clone” and “shallow clone” on some websites or blogs. Actually, this is a good understanding. Today we will analyze them hereJS deep copy and shallow copy

Shallow copy

Let’s use an example to illustrate JS shallow copy:

var n = {a: 1, b: 2}
var m = n
m.a = 12
console.log(n.a) // ?

Obviously aboven.aThe value of will change to 12, which is the JS shallow copy.Shallow copy is only a pointer to the object of the copy, in essence, it still points to the same object.

Deep copy

Also, let’s use an example to explain what it’s calledjs deep clone

var n = {a: 1, b: 2}
var m = {a: n.a, b: n.b}
m.a = 12
console.log(n.a) // ?

The above output is obviously the same1M and N although all the attributes and values are the same, they are two different objects. They occupy two different memory addresses in the heap memory, which is called deep copy.Deep copy is to copy a new object completely, which occupies two different memory addresses in heap memory.

JS implementation of deep copy

Simple one dimensional data structure

  1. Manual direct assignment

The deep copy example above

  1. Using ES6Object.assign()Method
const obj = {name: 'cc', age: 24}
const newObj = Object.assign({}, obj) = 'cc1' ? // cc

Two dimensional data structure and above

  1. Simple and crude way:JSON.parse(JSON.stringify(obj))

Disadvantages: it can’t make deep copy for regular expression type, function type, etc., and it will directly lose the corresponding value, and it will discard the objectconstructor

var obj = { a: {a: "cc"}, b: 123 }
var newObj = JSON.parse(JSON.stringify(obj))
newObj.b = 1234
console.log(obj)   // {a: {a: 'cc'}, b: 123}
console.log(newObj);    // {a: {a: 'cc'}, b: 1234}
  1. Using jquery
// shallow copy
var newObj = $.extend({}, obj)

// deep copy
Var newobj = $. Extend (true, {}, obj) // the first parameter must be true
  1. Implement a simple deep copy function by yourself
function deepClone(obj){
  if(typeof obj !== "object" || obj === null) return    
  let newObj = obj instanceof Array ? [] : {}
  for(let key in obj){
        newObj[key] = typeof obj[key] === "object" && obj[key] !== null ? deepClone(obj[key]) : obj[key]
  return newObj
let obj = {a: 1, b: function(){}, c: {d: 2}}
deepClone(obj)  // {a: 1, b: function(){}, c: {d: 2}}

These methods are the most commonly used methods for deep copy. Of course, there are other libraries, such asdeepCopylodashWait, we won’t go deep here.

Recommended Today

The way of nonlinear optimization

Mathematical knowledge 1、 Nonlinear functionLinear function is another name of a function of first degree, then nonlinear function means that the function image is not a function of a straight line.Nonlinear functions include exponential function, power function, logarithmic function, polynomial function and so on. 2、 Taylor expansion1. Taylor formula:Taylor’s formula is to add a_ The […]