JS for shallow copy and deep copy

Source: Internet
Author: User
Tags hasownproperty

Both shallow and deep copies are only for complex objects such as Object, array,

Difference: Shallow copy copies only the first-level properties of objects, deep copies can recursively replicate the properties of an object

If an array element is a basic type, it will be copied, not affected, and if it is an object or an array, it will only copy objects and arrays of references, so that if we modify the old and new arrays, both will change, this is called a shallow copy.

A deep copy is a complete copy of an object, even if the object is nested, and the two are separated from each other, modifying the properties of one object without affecting the other.

One, shallow copy

1, shallow copy of the array

(1), can be used concat, slice return a new array of attributes to achieve the copy

var true NULL , undefined]; var // or var New_arr = Arr.slice () is the same effect; New_arr[0] = ' new '//  ["old", 1, true, null, undefined]//  ["New", 1, true, NULL , UNDEFINED]/2,

(2), as well as a For loop can also achieve a shallow copy of the array

var arr = [1,2,3,4,5]var arr2 = Copyarr (arr)function  Copyarr (arr) {     = []    for (Let i = 0; i < arr.length; i++) {     res.push (Arr[i])    }    
    return  res}

(3), ES6 extension operator to implement a shallow copy of an array

var arr = [1,2,3,4,5]var [... arr2] = arrarr[2] = 5console.log (arr) Console.log (ARR2)

But if an array is nested with an object or array, the concat, slice copy will cause the old and new arrays to change as long as they are modified, such as:

var arr = [{old: ' old '}, [' old ']; var new_arr = arr.concat (); arr[0].old = ' new '; new_arr[1][0] = ' new '// [{old: ' new '}, [' New ']] // [{old: ' new '}, [' New ']]

2. Shallow copy of Object

(1), Universal for loop

var obj = {  ' Fungleo ',  ' man ',  ' + '}var obj2 =  Copyobj (obj)function  copyobj (obj) {  = {}  for (var   in obj) {    = Obj[key]  }  return  res}

(2), ES6 extension operator to implement a shallow copy of the object

var obj = {  ' Fungleo ',  ' man ',  ' + '}var {... obj2} == ' console.log '(obj) console.log (obj2)

Also, if the object is nested inside other incoming data types, the shallow copy of the object does not make a real copy of the deep stuff.

Object.assign () can also be used to make shallow copies of arrays and objects

Here is a general approach to shallow copy, the realization of the idea: to traverse the object, attribute and attribute values are placed in a new object

varShallowcopy =function(obj) {//Copy objects only  if(typeofObj!== ' object ')return; //determines whether to create a new array or an object based on the type of obj  varNEWOBJ = objinstanceofArray? [] : {}; //iterates over obj and determines that it is a property of obj to copy   for(varKeyinchobj) {    if(Obj.hasownproperty (key)) {Newobj[key]=Obj[key]; }  }  returnNEWOBJ;}

Second, deep copy

The following is a common method of deep copy, realizing the idea: when copying the type of the property value, if it is an object, continue to call the deep copy function recursively

varDeepcopy =function(obj) {//Copy objects only  if(typeofObj!== ' object ')return; //determines whether to create a new array or an object based on the type of obj  varNEWOBJ = objinstanceofArray? [] : {};  for(varKeyinchobj) {    //iterates over obj and determines that it is a property of obj to copy    if(Obj.hasownproperty (key)) {//determines the type of the property value, if the object recursively calls a deep copyNewobj[key] =typeofObj[key] = = = ' object '?deepcopy (Obj[key]): Obj[key]; }  }  returnNEWOBJ;}

There is also a more practical deep copy technique:

function deepcopy (obj) {    return  json.parse (json.stringify (obj));}

However, there are some drawbacks to this approach, such as inability to handle function, inability to process Reg, inability to process circular reference objects, but generally enough

JS for shallow copy and deep copy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.