JavaScript: array deep copy

1 The significance of array deep copy

Array deep copy in JavaScript refers to creating a new array that is completely independent of the original array, and all elements of the new array are copies of the original array. A deep copy is the creation of a completely independent copy within an array or object so that it can be modified without affecting the original array or object.

Array deep copying is a very important technique because if you simply copy one array into another, they will share the same memory address, which means that if one array changes, the other will also be affected .

A deep copy ensures that each array is independent and can be modified without affecting the original array. This is very important for code correctness and maintainability.

2 Common methods of array deep copy

2.1 Using JSON serialization and deserialization

Here's an easy way to do a deep copy by converting an array object to a JSON string and then converting it back to an array object. However, it should be noted that this method cannot copy special objects such as functions and regular expressions.

var originalArray = [1, 2, 3];
var copiedArray = JSON.parse(JSON.stringify(originalArray));

2.2 Using recursive methods

Iterates through the array recursively and copies each element into a new array. If the element is still an array, the recursive method is used again for deep copying.

function deepCopyArray(arr) {
    
    
  var copiedArray = [];
  for (var i = 0; i < arr.length; i++) {
    
    
    if (Array.isArray(arr[i])) {
    
    
      copiedArray.push(deepCopyArray(arr[i]));
    } else {
    
    
      copiedArray.push(arr[i]);
    }
  }
  return copiedArray;
}

var originalArray = [1, 2, [3, 4]];
var copiedArray = deepCopyArray(originalArray);

This method can handle deep copying of multidimensional arrays, but for arrays containing special objects such as functions and regular expressions, deep copying still cannot be performed.

2.3 Using third-party libraries

If you don't want to implement the deep copy logic yourself, you can use some third-party libraries to implement it. For example, the cloneDeep method in the lodash library implements a deep copy.

var _ = require('lodash');
var originalArray = [1, 2, [3, 4]];
var copiedArray = _.cloneDeep(originalArray);

In this way, the deep copy of the array can be realized conveniently, and it also supports the copying of special objects.

Guess you like

Origin blog.csdn.net/weixin_46098577/article/details/132077987
Recommended