Deep copy and shallow copy understood and implemented

In js copied between the object and the array into deep copy and shallow copy, i.e. shallow copy is a single copy of an object copied to another variable or array, in which case both point to the same array, quiet and that we look at an example:

A = {OBJ1 the let:. 3, B:. 4, Z: {X:. 5, T:. 6 }} 
 // assign this object to another object, a method implemented shallow copy

 

obj2 = Object.assign the let ({}, OBJ1)    // ASSIGN achieve shallow copy
  = {... OBJ1 OBJ3 the let} // for ES6 destructuring assignment to achieve shallow copy
 function copy(obj){
   if(obj == null) return 
   let type = obj.toString().slice(8,-1)
   let result =(type == "Object")? {}: []
   for(let i in obj){
    result[i] = obj[i]
   }
  return result
}
 let obj4 = copy(obj1)
//用for...in 的方法实现浅拷贝

The above three methods can be realized shallow copy

obj1, obj2.obj3, obj4, when I gave a time in which the object inside the object of an assignment, the other corresponding value will change

As results

These are shallow copy, the following describes a deep copy.

Whether that is a deep copy objects or how many objects the following array or array can be copied into another variable to the

I used two methods to achieve

 function truedeep(obj) {

      let type = obj.toString().slice(8, -1)  //用toString方法判断obj的
//类型。
      let result = (type == "Object") ? {} : []  
      if (type != "Object" && type != "Array") return obj
      if (type == "Array") {
        for (let i = 0; i < obj.length; i++) {
          result.push(truedeep(obj[i]))   //用递归逐层剖开
        }
      } else {
        for (i in obj) {
          result[i] = truedeep(obj[i])
        }
      }
      return result
    }


    let obj5 = truedeep(obj1)
    let obj6 = JSON.parse(JSON.stringify(obj1))
//用JSON的方法实现深拷贝

同样的测试,效果如图

可见深拷贝是完完全全把一个对象拷贝到另一个对象,且从此两者都没有多大关系了。

Guess you like

Origin www.cnblogs.com/388ximengpy/p/12150044.html