Deep copy and shallow copy (classic interview)

Let you fully understand the difference between deep copy and shallow copy in JavaScript

  1. deep copy
  2. shallow copy

First, let's take a look at the types:

Basic data types: string (String) , value (Number) , Boolean (Boolean) , undefined (Undefine) , empty value (null) ;

Reference data type: array (Array) , object (Object) , function (Function) .

Values ​​of reference data types are objects stored in stack memory and heap memory. The stack area memory holds the variable identifier and the pointer to the object in the heap memory. When looking for a reference value, the interpreter first looks for an address on the stack. Then find the entity of the heap memory according to the address.

What is deep copy:

Deep copy is to copy an object from the memory completely , and open up a new area from the heap memory to store the new object.

What is a shallow copy:

What the variable saves is not the object itself, but the address pointing to the object . At this time, if the content of the object itself is changed, the display content of other variables will also change; if the attribute is a basic type, the value of the basic type is copied ; if the attribute is a reference type, copy is the memory address  .

What is the difference between deep copy and shallow copy?

  • Deep copy changes the new object without affecting the original object, and they do not affect each other;
  • The basic types of shallow copy do not affect each other before. If one object of the reference type changes its address, it will affect the other object.

Simple understanding: It is assumed that B copied A. When A is modified, check whether B will change. If B also changes, it means that this is a shallow copy, and the manpower is short. If B does not change, it is a deep copy. .

Next, let's use a simple case to understand:

Deep copy:

Use the JSON.stringify() method

const list3= [{name:'张亮'}]
        const listCopy2 = JSON.parse(JSON.stringify(list3))
        listCopy2[0].name = '王五'
        console.log(list3);
        console.log(listCopy2);

case:

function deepCopy(obj5){
          if(typeof obj5 !== "object" || obj5 === null){
            return obj5
          }else if(Array.isArray(obj5)){
            var arr = []
            for(var i=0;i<obj5.length;i++){
              arr.push(deepCopy(obj5[i]))
            }
          }else if(obj5 instanceof Date){
            return new Date(obj5)
          }else if(obj5 instanceof String){
            return new String(obj5)
          }else if(obj5 instanceof Number){
            return new Number(obj5)
          }else if(obj5 instanceof Boolean){
            return new Boolean(obj5)
          }else{
            var newObj = {}
            for(var i in obj5){
              newObj[i] = deepCopy(obj5[i])
            }
          }
        }
        var obj5 = {
          str : "strjkgfd",
          num : 13,
          arr :[2,4,6,7,56,"dggfd",[2,4.6]],
          obj : {a:1,b:2,arr2:["a","b"],obj5:{a:2}},
          date : new Date()
        }
        var obj6 = deepCopy(obj5)

operation result:

 

shallow copy:

Copy using the [...list] method

// 第一种方法
        const list = [{name:'张三'}]
        const copylist = [...list]
        copylist[0].name = '李四'
        console.log(list);
        console.log(copylist);

Use the slice() method to copy

 // 第二种
        const list1 = ['张三','李四']
        const listCopy = list1.slice()  //slice()方法
        listCopy.push('王五')
        console.log('list:'+ list);
        console.log('listCopy:' + listCopy);

Use the Array.from() method to copy

const list2 = ['张三','李四']
        const listCopy1 = Array.from(list2) //Array.from()方法
        listCopy1.push('王五')
        console.log('list2:'+ list2);
        console.log('listCopy1:' + listCopy1);

Do you understand? 

Guess you like

Origin blog.csdn.net/Z_CH8648/article/details/127821532