First, superficial cloning
1. By calling Oldarr.concat () or oldarr.slice ();
2. In a shallow copy, if the element of the original array is a complex type, the element value points to the object's reference rather than the object itself, and the element value of the shallow copy also points to the object's reference, as is the original array, and any changes to the object
Affects point to object (reflected in two arrays)
Second, deep cloning
1. In the deep clone copy, the index is copied continuously, and all the objects in the original array are copied, so that the new array and the original array point to different objects
2. The deep clone code is implemented as follows:
/** * * * @authors Soul ([email protected]) * @date 2016-05-22 18:15:28 * @version 0.0.1 * @description Clone a Ar Ray as deep or shallow. * *//** * * @param oldarr the array to be cloned * @param deep depth Clone (Value=true/false), default to false* @param NEWARR returns a new array of clones * @return Array Returns a new array of clones **/functionClone (oldarr,deep) {//determine if deep cloning is done varIsdeep,newarr=[]; if(arguments.length==1) {Isdeep=false; } if(arguments.length==2) {Isdeep=Deep ; }Else{ Throw NewError ("parameter is incorrect"); return; } //Clone Start if(isdeep) {//Deep Clone Oldarr====>newarr for(varIinchOldarr) { varprop=Oldarr[i]; //Oldarr element is an object if(typeofprop== "Object"){ //the element is an array object if(PropinstanceofArray) { //newarr[i]=[]; for(varj=0;j<prop.length;j++){ if(typeofProp[j]!= ' object ') {Newarr[i].push (prop[i]); }Else{Newarr[i]=clone (prop,true); } } }Else{//the element is a non-array object //to create a new object, point to a new reference varnewprop={}; for(varattrinchprop) {eval ("Newprop." +attr+ "=" + "'" +prop[attr]+ "'"); } Newarr[i]=Newprop; } }Else{//Oldarr element is not an objectnewarr[i]=prop; } } }Else{ //superficial cloning of Oldarr===>newarrNewarr=Oldarr.concat (); } //Clone End returnNEWARR;}
3, the test is as follows:
Cloning an array