SoFunction
Updated on 2025-03-04

Analysis of the concepts and usage of JavaScript deep copy and shallow copy

This article describes the concepts and usage of deep copy and shallow copy in JavaScript. Share it for your reference, as follows:

shallow and deep copies in js are only for complex data types (ObjcetArray) copy issue. Simply put, both shallow copy and deep copy can achieve the effect of generating a copy based on the original object. However, according to whether the newly generated object can affect the original object, it can be divided into shallow copy and deep copy.

Concept 1: shallow copy

A shallow copy refers to copying references. The newly generated reference and the original reference both point to instances of the same object, and their operations will affect each other.

Concept 2: Deep Copy

Re-open memory in the heap and copy all the contents in the object instance corresponding to the original reference, so as to ensure that the deep-copied object and the original object are completely isolated and have no influence on each other.

Concept 3: Implementation of deep copy arrays

1. Useforcycle

<script type="text/javascript">
  var arr1=['a','b','c'];
  var arr2=[];
  function deepCopy(arr1,arr2){
    for(var i=0;i<;i++){
      arr2[i]=arr1[i];
    }
  }
  deepCopy(arr1,arr2);
  arr2[1]='d';
  (arr1);//['a','b','c']
  (arr2);//['a','d','c']
</script>

2. Useslice()method

<script type="text/javascript">
  var arr1=['a','b','c'];
  var arr2=(0);
  arr2[1]='d';
  (arr1);//['a','b','c']
  (arr2);//['a','d','c']
</script>

3. Useconcatmethod

<script type="text/javascript">
    var arr1=['a','b','c'];
    var arr2=();
    arr2[1]='d';
    (arr1);//['a','b','c']
    (arr2);//['a','d','c']
</script>

Concept 4: Deep copy of objects

1. Useforcycle

<script type="text/javascript">
  var obj = {
    name: 'FungLeo',
    sex: 'man',
    old: '18'
  }
  function copyObj(obj) {
    let res = {}
    for (var key in obj) {
      res[key] = obj[key]
    }
    return res
  }
  var obj2 = copyObj(obj);
  obj2["name"]="kka";
</script>

2. With the help ofJSONTo achieve

<script type="text/javascript">
  var obj = {
    name: 'FungLeo',
    sex: 'man',
    old: '18'
  }
  var obj2=((obj));
  obj2["name"]="kka";
</script>

Summary: The above are some common methods to implement deep copying of arrays and objects. You can use appropriate methods in combination with specific situations.

For more information about JavaScript, please view the special topic of this site: "JavaScript object-oriented tutorial》、《Summary of json operation skills in JavaScript》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.