Deep and shallow copies in JavaScript

Source: Internet
Author: User
var obj = {a:1, arr: [};var] obj1 = obj;            Shallow copy var obj2 = deepcopy (obj);  Deep copy

The object created in JavaScript is a storage address, and the result of a shallow copy is that both obj and Obj1 point to the same address, and if any of the one by one elements in obj or obj1 are modified, it will affect the other

OBJ.A = 2;console.log (obj1.a); 2

A deep copy is one that copies all the properties of an object and creates a space in another area to store these properties

var myObj = {str: "myString", Num:1,myarr: [{arrgo: "I Am Go"}],obj: {innerobj: {test:25},innerstr: "myobjstring"}}// Deep copy function deepcopy (obj) {var ret, k, B;ret = (obj instanceof Array)? []: {};for (k in obj) {if ((Obj[k] instanceof Array) | | (Obj[k] instanceof Object)) {//using recursion to copy attributes from obj to ret[k] = Clone (Obj[k]);} else {Ret[k] = obj[k];}} return ret;}

  

Deep and shallow copies in JavaScript

Related Article

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.