Shallow depth of replication and replication objects javascript arrays and assign / slice / concat / JSON.parse (JSON.stringify ())

depth and shallow copy arrays javascript objects and replication
in the normal use of our '=' to refer to an array or an object with a variable here is the 'reference' rather than copying the example below we see a reference copy and what concepts

ARR = var [1,2,3, 'f', 2 , 's ',. 1]; 
var cloneArr = ARR; // time cloneArr indeed [1,2,3,' f ', 2 ,' s ', 1] 
// we have to look at the print 
console.log (cloneArr); // let's print it and see [, 2, 3,' f ', 2,' S ', 1] 
console.log (arr ); // this is the same [l, 2,3, 'F', 2, 'S',. 1] 

// print the results
[1,2,3, "f", 2 , "s", 1]
[1,2,3,"f",2,"s",1]

But when we change an array element, we look at what happens

arr [0] = 'Bob' ; 
the console.log ( 'ARR:' + ARR); // this is a printing [ "Bob", 2, 3, "f ", 2, "s", 1] without any problem 
the console.log ( 'cloneArr:' + cloneArr); // we print what has changed cloneArr found [ "Bob", 2,. 3, "F", 2, "S",. 1] 

// we try to change cloneArr, and see what happens 

cloneArr.push ( 'I am cloneArr' ); 
console.log ( 'arr:' + arr); // [ "Xiao Ming", 2, 3, "f ", 2, "s" 1, "I am cloneArr"] 
the console.log ( 'cloneArr:' + cloneArr); // this is also changed [ "Bob", 2, 3, "f ", 2, "s", 1, " I is cloneArr "] 

// print result
arr: Xiaoming, 2,3, f, 2, s ,1
cloneArr: Xiao Ming, 2,3, f, 2, s , 1
arr: Xiao Ming, 2,3, f, 2, s , 1, I cloneArr
cloneArr: Xiao Ming, 2,3, f, 2, s , 1 I was cloneArr

We look at an example of an object is also a reason

var obj = { 
        name: 'Bob' , 
Age: 18 is , 
Tel: '13,108,123,123' , 
Sex: 'M' 
    }; 
cloneObj = obj; 
cloneObj [ 'name'] = 'red' ; 
the console.log (obj); // {name: "red", age: 18, tel: "13108123123", sex: " M"} 
// print result:
Object {name: "red", age: 18, tel: "13108123123", sex: "Male"}

In development in general do not want this to happen we have to use a copy of this function Here we introduce what are copied, a deep copy and shallow copy What is the difference

First, the depth of the array are copied
1. We first look at the array shallow copy of some of the ways slice concat shallow copy when no function for looping through not say so unnecessary,
an array shallow copy under normal circumstances can be resolved with a slice and concat, we look at the example

var ARR = [l, 2,3, 'F', 2, 'S',. 1 ];
 var cloneArr1 = arr.slice ();
 var cloneArr2 = arr.concat (); 
the console.log ( 'no changes before: '+' \ n-'+ arr +' \ n-'+ cloneArr1 +' \ n-'+ cloneArr2); // is the same 

// for convenience see different elements where each change 
arr [0] =' I was the first to arr a ' ; 
cloneArr1 [ 1] =' I am the second cloneArr1 ' ; 
cloneArr2.push ( ' I am cloneArr newly added ' ); 

// we print it and see 
console.log (' after the change: '+ '\ n-' + ARR + '\ n-' + cloneArr1 + '\ n-' + cloneArr2); 

// print the results
before the change:
l, 2,3, F, 2, S,. 1
1,2,3,f,2,s,1
1,2,3, f, 2, s, 1 
after the change:
I am the first of arr, 2, 3, f, 2, S, 1
1, I is the second of cloneArr1, 3, f, 2 , S, 1
, 2, 3, f, 2, S, 1, I was newly added cloneArr

From the above example can be seen when we put a new array or mosaic array taken and returned to the original array is not a reference relationship, but rather a new independent arrays, the specific description can be seen in the slice and https Array of concat: / /blog.csdn.net/xiaoxiaoshuai__/article/details/77840759

The above may seem easy to complete a shallow copy,
then we look to build a two-dimensional array of light can copy it to complete the task
we look at this example

var arr2 is = [1,2,3,4,5,6,7, [ 'Q', 'W', 'E', 'W'],. 8, {name: 'Bob', age: 18}, 9,7,54 ];
 var cloneArr1 = arr2.slice ();
 var cloneArr2 = arr2.concat (); 
the console.log (arr2 is); // is the same as 
the console.log (cloneArr1); // is the same 
console .log (cloneArr2); // is the same 

// we have to try this element here 
arr2 [0] = 101 ; 
console.log (arr2); // change the [101,2,3,4,5, 6,7, [ 'q', ' w', 'e', 'w'], 8, {name: ' Bob', Age: 18 is}, 9,7,54]; 
the console.log (cloneArr1); // not changed [1,2,3,4,5,6,7, [ 'q', 'w', 'e', 'w'], 8, {name: ' Bob', age: 18} ,9,7,54];
console.log(cloneArr2); //Not changed [1,2,3,4,5,6,7, [ 'q', 'w', 'e', 'w'], 8, {name: ' Bob', age: 18}, 9 , 7,54]; 

// seemingly no problem, we try to change it two array elements inside 
arr2 [7] [2] = 'eee000' ; 
console.log (arr2); // change the [ 101,2,3,4,5,6,7, [ 'q', ' w', 'eee000', 'w'], 8, {name: ' Bob', age: 18}, 9,7 , 54]; 
console.log (cloneArr1); // this also changed how? [1,2,3,4,5,6,7, [ 'q', 'w', 'eee000', 'w'], 8, {name: ' Bob', age: 18}, 9,7 , 54]; 
console.log (cloneArr2); // this also changed how? [1,2,3,4,5,6,7, [ 'q', 'w', 'eee000', 'w'], 8, {name: ' Bob', age: 18}, 9,7 , 54];


Then we found two arrays using these methods seems does not work,
then we try to JSON.parse (JSON.stringify ()) method to solve it;

var ARR3 = [1,2,3,4,5,6,7, [ 'Q', 'W', 'E', 'W'],. 8, {name: 'Bob', age: 18}, 9,7,54 ];
 var cloneArr1 = the JSON.parse (the JSON.stringify (ARR3)); 

the console.log (ARR3); // [1,2,3,4,5,6,7, [ 'Q' , 'w', 'e' , 'w'], 8, {name: ' Bob', Age: 18 is}, 9,7,54]; 
the console.log (cloneArr1); // successfully copied the [1 , 2,3,4,5,6,7, [ 'q', 'w', 'e', 'w'], 8, {name: ' Bob', age: 18}, 9,7,54 ]; 

// then we look to change the value of 
ARR3 [0] = 101 ; 
ARR3 [ . 7] [. 1] = 'qqqpppqqpp' ; 
ARR3 [ . 9] [ 'name'] = 'fly overhead' ; 

the console.log (ARR3 ); // [101,2,3,4,5,6,7, [ 'Q','qqqpppqqpp', 'e', 'w'], 8, {name: ' fly overhead', Age: 18 is}, 9,7,54]; 
the console.log (cloneArr1); //This seems to be [1,2,3,4,5,6,7, [ 'q', 'w', 'e', ​​'w'], 8, {name: 'Bob', age: 18}, 9,7,54];


With JSON.parse (JSON.stringify ()) as if all is well, copying solved, let us look to see complex data

function Fn1 (Age) { 
    Alert (Age); 
} 
var B = "BBB" ;
 var ARR3 = [6, 7 are, [ 'Q', 'W', 'E', 'W'],. 8, {name: 'Bob', Age: 18 is, Fn: function (name) {Alert (name);}}, 9,7,54 , Fn1, B];
 var cloneArr1 = the JSON.parse (the JSON.stringify (ARR3)) 
Console. log (ARR3); // [, 6, 7 are, [ 'Q', 'W', 'E', 'W'],. 8, {name: 'Bob', age: 18, fn: function (name) Alert {(name);}}, 9,7,54, function function, 'BBB']; 
the console.log (cloneArr1); // [6, 7 are, [ 'Q', 'W', 'E', 'w'], 8, { name: ' Bob', age: 18}, 9,7,54 , null, 'bbb']; fn which is found in the function and the function name is not copied


We found JSON.parse (JSON.stringify ()) can not be replicated with an array of functions, which should how to do it

Let's look together said object replication, behind


Second, the depth of the object replication
methods array shallow copy of our first look assign

function Fn2 (Age) { 
    Alert (Age); 
} 
var obj = { 
    name: 'Bob' , 
    Age: 18 is , 
    Tel: '13,108,123,123' , 
    Sex: 'M' , 
    Fn: function (name) { 
        the console.log (name ) 
    }, 
    fn2: fn2 
}; 
cloneObj = Object.assign ({}, obj); 
console.log (obj); 
console.log (cloneObj); // here successfully copied 

// we try to change 

obj [ ' name '] =' red ' ; 
the console.log (obj); // change
console.log (cloneObj); // No change


This copy is successful, the object is normal, and if we are about to try again a bit more complex

function fn2(age){
    alert(age);
}
var obj={
    name:'小明',
    age:18,
    tel:'13108123123',
    sex:'男',
    fn:function(name){
        console.log(name)
    },
    fn2:fn2,
    obj2:{
        name:'小红',
        age:16
    },
    li:[12,23,45,23]
};
cloneObj=Object.assign({},obj);
console.log(obj);
console.log(cloneObj); // here successfully copied 

// we try to change 

obj [ 'name'] = 'little red' ; 
obj [ 'obj2'] [ 'name'] = 'small obviously' ; 
obj [ 'li'] [ . 1] = 900 ; 
the console.log (obj); // change 
the console.log (cloneObj); // obj name is not changed, but the name and obj2 obj value has changed in li


After the complicated seem Object.assign not complete the task, and
that we use JSON.parse (JSON.stringify ()), try to see it can be a problem

= cloneObj JSON.parse (JSON.stringify (obj)); 
console.log (obj); 
console.log (cloneObj); // here successfully copied 

// we try to change 

obj [ 'name'] = 'small red ' ; 
obj [ ' obj2 '] [' name '] =' obviously small ' ; 
obj [ ' Li '] [. 1] = 900 ; 
the console.log (obj); 
the console.log (cloneObj); // from Print results, in addition to the other functions can be deep copy


It seems to be, but we remember JSON.parse (JSON.stringify ()) can not copy functions and function variables

In summary:

Shallow copy an array: slice, concat

Array deep copy: JSON.parse (JSON.stringify (arr)) ; insurmountable functions and function with the array variables
objects shallow copy: Object.assign ({}, obj) 
Object deep copy: JSON.parse (JSON. stringify (arr)); insurmountable object with variable functions and function


Then we look at is there are an array of multi-layer objects or functions how to solve it

Well, Baidu not found himself encapsulates a way to implement it

function fn2(age){
    alert(age);
}
var obj={
    name:'小明',
    age:18,
    tel:'13108123123',
    sex:'男',
    fn:function(name,a,b){
this.name=name;
this.fnn=function(a,b){
            console.log(a+b)
}
    },
    fn2:fn2,
    obj2:{
name:null,
sex:'男',
age:15
    },
    Li: [ . 1, null , 0,23 ], 
    LiI: [ 1,2,3,4,45, [1,2,3,43,3, {name: '111', Age: '. 1', E : [2,3,4,1,1,2], FNNC: function () {the console.log (. 11);}}], 3,2- ,] 
}; 

// we look at the average 0.4 copy ~ 0.9 ms before 
console.time ();
 var cloneObj2 = clone (obj); // clone user-defined function here to buy shut ~ @ @ 
console.timeEnd (); 


obj [ 'name'] = 'red red words' ; 
obj [ 'obj2'] [ 'name'] = 'flower that flower' ; 
obj [ 'LiI'] [. 5] [. 1] = '5656565' ; 
obj [ 'LiI'] [. 5 ] [5] [ 'name' ] = ' big Red' ; 

the console.log (obj);// has changed 
console.log (cloneObj2); // not changed, ok can 

// we look at the function replication 

cloneObj2 [ 'Fn2'] (16); // normal pop 16


According to the simulation test data can be copied by more than the depth of the problem should not be a problem, the source code below, a little more than a few lines of code, screenshots small word are interested can download the source code to see on Git: https: //github.com/liushuai541013304/ oject-deep-clone
do not want to download messages can be directly under, the landlord will offer @ ~ @ obediently.

Guess you like

Origin www.cnblogs.com/m2maomao/p/10930374.html