Copy depth on the array, object

Shallow copy

And an array of objects as reference types JS, direct use of the assignment "=", then, will address the source array, the object is assigned to the new array object does not implement data copy array shallow copy is achieved in this way. When assigned to another variable, in fact, is to point to another variable with the same address, when we change one time, actually changes the memory contents of heap memory, all point to an array corresponding to the address takes place change

Deep copy

Deep copy is to redistribute a new storage space, two different addresses corresponding to the object, wherein a modified value, does not affect the value of another object

Sometimes we hope that the new object or array obtained from the original object or an array of influence, so we need a deep copy

Deep copy of the array

Concat using slice and methods, and for ES6 [... ARR], an array of loop

  1. let newarr = […arr]
  2. concat () method is used to connect two or more arrays. This method does not change the existing array, but will only return a copy of the array are connected to
    let newarr = arr.concat ()
  3. array.slice (start, [end]) ignored then slice method has been copied to the array of end
    let arr = arr.slice (0)
  4. Loop through
var arr1 = [1,2,3];//原来数组
var arr2 = [];//新数组

function deepCopy(arry1, arry2){
  var length = arry1.length;
  for(var i = 0;i<length;i++){
    arry2[i] = arry1[i];
  }
}

slice, concat method, and for ES6 [... ARR] limitations:
if the array is an array of values inside the object, then it will find a deep copy does not work
due to the internal array reference object attribute value, and therefore using slice concat copy of the object on the array, the entire copy or shallow copy, and then copy each array of pointers to the value or point to the same memory address.
Thus, slice and concat these two methods, only for one-dimensional array of deep copy does not contain the object reference

For deep copy of the array object, it can be converted to a string manner employed

let newarr = JSON.parse(JSON.stringify(arr))

This way you can solve the problem of considerable part of the assignment, but some special properties except for (undefined / function)

Deep copy of an object

ES6 deep copy of the object {... obj}, Object.assign ({}, obj)

  1. let newobj = {…obj }
  2. let newobj = Object.assign({}, obj )

Taken together
let newarr = JSON.parse(JSON.stringify(arr))can solve most of the problems of deep copy

Published 137 original articles · won praise 30 · views 260 000 +

Guess you like

Origin blog.csdn.net/hani_wen/article/details/103976851