Detailed description of shallow copy and deep copy in javascript

Source: Internet
Author: User
This article mainly introduces the shallow copy and deep copy code of JavaScript objects in detail, which has some reference value. If you are interested, you can refer to it. the following small series will bring you an article on object-oriented deep copy and shallow copy in JavaScript. I think this is quite good. Now I will share it with you and give you a reference.

1. Shallow copy: copy a reference. All referenced objects point to a copy of data and can modify the data.

2. Deep copy (complex): copy the variable value. For non-basic types of variables, recursive to the basic type variables before copying.

Here we will draw a simple figure to deepen our understanding:

When using JavaScript to operate the array, we often need to back up the array. It turns out that if we simply assign it to other variables, we only need to change any of them, and the others will change, which leads to the problem.

Var arr = ["One", "Two", "Three"]; var arrto = arr; arrto [1] = "test"; document. writeln ("original array value:" + arr +"
"); // Export: Original Value of the array: One, test, Threedocument. writeln (" New Value of the array: "+ arrto +"
"); // Export: New Value of the array: One, test, Three

The direct assignment method like above is the shallow copy. In many cases, this is not the result we want. In fact, what we want is that the value of arr remains unchanged, isn't it?

Method 1: js slice Function

Var arr = ["One", "Two", "Three"]; var arrtoo = arr. slice (0); arrtoo [1] = "set Map"; document. writeln ("original array value:" + arr +"
"); // Export: Original Value of the array: One, Two, Threedocument. writeln (" New Value of the array: "+ arrtoo +"
"); // Export: New Value of the array: One, set Map, Three

Method 2: concat method of js

Var arr = ["One", "Two", "Three"]; var arrtooo = arr. concat (); arrtooo [1] = "set Map To"; document. writeln ("original array value:" + arr +"
"); // Export: Original Value of the array: One, Two, Threedocument. writeln (" New Value of the array: "+ arrtooo +"
"); // Export: New Value of the array: One, set Map To, Three

Ii. Object copying

var a={name:'yy',age:26};var b=new Object();b.name=a.name;b.age=a.age;a.name='xx';console.log(b);//Object { name="yy", age=26}console.log(a);//Object { name="xx", age=26}

It is to traverse the attributes of an object and assign it to a new object.

var deepCopy= function(source) { var result={};for (var key in source) { result[key] = typeof source[key]==='object'? deepCoyp(source[key]): source[key]; }  return result; }

Here is an example of jQuery:

JQuery. extend = jQuery. fn. extend = function () {// 1. extend the extend Method to the JQ (function): Expand the static method // 2. jQuery. fn. extend extends extend to jq. under fn and jQuery. fn = jQuery. prototype extension instance method // 1. 2. similar functions: var options, name, src, copy, copyIsArray, clone, // define some variables target = arguments [0] | {}, // The target element is the first element of [0] $. extend (a, {name: 'hello'}, {age: 30}); I = 1, // the length of the first element = arguments. length, // the element of the first object deep = false; // whether the object is a deep copy Recognize false not // Handle a deep copy situation to see if it is a deep copy condition if (typeof target = "boolean") {// It is a boolean value deep = target; target = arguments [1] | |{}; // The target element is the second $. extend (true, a, B) // skip the boolean and the target I = 2;} // Handle case when target is a string or something (possible in deep copy) incorrect Parameter. if (typeof target! = "Object "&&! JQuery. isFunction (target) {// target = {} when the target is not an object or a function {}; // change to an empty jason} // extend jQuery itself if only one argument is passed to see if it is a plug-in. if (length = I) {// write only one object to extend this object to the jq source code static method or the instance method target = this; // this is $ or $ (); -- I ;} // There may be multiple objects for (; I <length; I ++) {// Only deal with non-null/undefined values if (options = arguments [I])! = Null) {// check whether all objects in the backend have values // Extend the base object for (name in options) {src = target [name]; copy = options [name]; // Prevent never-ending loop if (target = copy) {// prevents loop reference to continue; // jump out of this loop and continue executing // $. extend (a, {name: })); loop reference a is also an object} // Recurse if we're re merging plain objects or arrays deep copy if (deep & copy & (jQuery. isPlainObject (copy) | (copyIsArray = jQuery. isArray (copy )))) {// It is a deep copy and requires var B = {name: {age: 30}. B must be an object independent variable (jason) or an array // recursive if (copyIsArray) {// array copyIsArray = false; clone = src & jQuery. isArray (src )? Src: []; // defines an empty array} else {// jason clone = src & jQuery. isPlainObject (src )? Src: {}; // check whether the original property exists and whether jason defines an empty jason} // var a = {name: {job: 'it '}}; add // var B = {name: {age: 30 }}; // $. extend (true, a, B); // a inherits B // console. log (a); a {name: {job: 'it', age: 30} if there is only one {}, only, age: 30 // Never move original objects, clone (a) them target [name] = jQuery. extend (deep, clone, copy); // call the function itself for further recursive processing // Don't bring in undefined values shortest Copy} else if (copy! = Undefined) {target [name] = copy; // directly copy because there are no objects in it }}// Return the modified object return target ;};

The above is all the content of this article. I hope it will help you learn and support PHP.

For more javascript-related articles on shortest copy and deep copy, please follow the PHP Chinese network!

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.