javascript copy simple implementation shades

Copy depth knowledge still is used more in our daily development, but previous state has been heard only once, never use (in fact, spent just do not realize it), so today to chat with you in js copy depth;

  First, let's look at the javascript data types, our javascript There are six types of data in the js version of ES5, namely:

  Number (numeric), String (String), Boolean (Boolean), Object (subject, object, and all array type Object), null, undefined

  javascript copy depth we use every day is mainly for Object reference type copy;

  

  We know that the implementation of the operation object copy js shades the face, and then we'll look at the depth of copies of the concept:

     Copy is to copy the name implies, the memory is divided into a total of two stack memory and heap memory area, the so-called depth type is a reference copy of the primary copy of a data javascript, after shallow copy is a reference-type data assigned to each other, for example obj1 = obj2; if modified obj1 or obj2 latter operation, this time the data will change accordingly, since the type of reference data in memory in the heap, the heap memory is a value stored in the memory reference type, while there will be a pointer address points to the stack memory, two types of reference data address as another influential if one will change; it will not copy deep, deep copy will re-open up a space for storage in heap memory;

 

    Basic types of replication:

var a =. 1 ;
 var B = a; // copy 
the console.log (B) // . 1 
a = 2; // change a value of 
the console.log (B) // . 1 
the console.log (a) // 2

 

  Because a, b belong to the basic types, basic types of replication will not affect the other, as the basic type is created every time a memory variable will be opened in the stack memory, used to store value, the basic types of replication is not Another variable will have an impact;

 

    Copy reference types:

      Reference types of replicate our copy is divided into two aspects of replication and an array of objects to explain:

      js shallow copy:

var arr1 = ['red','green'];
var arr2 = arr1;//复制
console.log(arr2)//['red','green'];
arr1.push('black') ;//改变color1的值
console.log(arr2)//['red','green','black']
console.log(arr1) //["red", "green", "black"]

    The above case is a shallow copy javascript array, we can see by the above knowledge to know the array is a reference type data, data replication is a reference type will affect each other, we see arr1.push ( 'black') added a new child, because of the above var arr2 = arr this line is a reference to two types of address pointer point to the same data a heap memory region, whether or arr2 arr1 modification, a modification of any two arrays are mutually would impact; copy the above way of direct assignment that is what we often say that the reference type of shallow copy;

     About deep copy Many students mistakenly think that the native method concat js is, slice belongs to a deep copy, in fact, not of; js native method concat, slice are only for one-dimensional array, once the two-dimensional array or multidimensional array would there will be problems, there have not enough copies of the complete cause or another pulling data problems occur;

        slice:

var arr1 = ['red','green'];
var arr2 = arr1.slice(0);//复制
console.log(arr2)//['red','green'];
arr1.push('black') ;//改变color1的值
console.log(arr2)//["red", "green"]
console.log(arr1)//["red", "green", "black"]

      js native slice method returns a new array, the above code at first glance thought it was a deep copy, because arr2 and arr1 copy and pulling each other, and when arr1 called push method to add a new Array of children when, no arr2 changes; yes, this is in line with characteristic deep copy, but the copy is not complete, so it can not be regarded as a deep copy in the true sense, so slice can only be called a shallow copy; slice method only applies to one-dimensional array copy, will be full of flaws in a two-dimensional array;

      Here we look at the example of a two-dimensional array:

was Arr1 = [1,2,3, [ '1', '2', '3' ]];
was arr2 = arr1.slice (0 ); 
 Arr1 [ 3] [0] = 0 ; 
 console.log (Arr1); // [1,2,3, [ '0', '2', '3']] 
 console.log (arr2); // [1,2,3, [ '0', '2', '3']]

       The code is a two-dimensional array, when we make changes in the value of arr1 arr1 [3] [0] inside, we found arr1, arr2 two array values ​​have changed; it turns out that slice is not a deep copy;

 

      concat:

var arr1 = ['red','green'];
var arr2 = arr1.concat();//复制
console.log(arr2)//['red','green'];
arr1.push('black') ;//改变color1的值
console.log(arr2)//["red", "green"]
console.log(arr1)//["red", "green", "black"]

 

 

var arr1=[1,2,3,['1','2','3']];
var arr2=arr1.concat();
 arr1[3][0]=0;
 console.log(arr1);//[1,2,3,['0','2','3']]
 console.log(arr2);//[1,2,3,['0','2','3']]

      

       concat method will not affect the data in the source array of one-dimensional array, and in the two-dimensional array concat and slice the performance is the same;

 

 

      js deep copy:

      Js method to achieve a deep copy of the array are many, such as JSON.parse (JSON.stringify ()) as well as extend and recursive method JQuery library (just extend the method relies on JQuery library, so we try to use the native way to achieve ) are the deep copy may be implemented in arrays and objects;

var arr1 = ['red','green'];
var arr2 = JSON.parse(JSON.stringify(arr1));//复制
console.log(arr2)//['red','green'];
arr1.push('black') ;//改变color1的值
console.log(arr2)//["red", "green"]
console.log(arr1)//["red", "green", "black"]

     The code above we can clearly see JSON.parse (JSON.stringify ()) is to achieve a deep copy in the true sense;

    

         Recursive deep copy:

      

function deepClone(obj){
    //判断参数是不是一个对象
    let objClone = obj instanceof Object?[]:{};
    if(obj && typeof obj==="object"){
        for(key in obj){
            if(obj.hasOwnProperty(key)){
                //判断ojb子元素是否为对象,如果是,递归复制
                if(obj[key]&&typeof obj[key] ==="object"){
                    objClone[key] = deepClone(obj[key]);
                }else{
                    //如果不是,简单复制
                    objClone[key] = obj[key];
                }
            }
        }
    }
    return objClone;
}    

var a ={
    x:1,
    y:2
};


b=deepClone(a);
a.x=3
console.log(a);
console.log(b);

 

  输出效果如下:

  

 

 

 

    总结:

        1:深拷贝只是从源数据中拷贝一份出来进行操作,而不是改变源数据;改变源数据的那是浅拷贝;

        2:原生js方法slice、concat都不是真正意义上的深拷贝,都仅只适用于一维数组,拷贝的属性不够彻底;

        3:实现js深拷贝我们可以通过JSON.parse(JSON.stringify())、递归以及JQuery库的extend方法来实现;

     

 

Guess you like

Origin www.cnblogs.com/dengyao-blogs/p/11466598.html