Solving the reference problem of JS object with shallow/deep copy, and HTML5 method

Source: Internet
Author: User

First look at an example

Example one:

var a=[1,2,3]; var b=A;b.push (4); alert (b); // 1,2,3,4Alert (a); // 1,2,3,4
var a=[1,2,3]; var b=a;b=[1,2,3,4]alert (b); // 1,2,3,4Alert (a); //  the

The results of these two methods are different.

The first program, which is a reference to the object, gives the value of a a reference between B,a and B, and when the relationship is referenced, changing either variable will affect the other variable.

The second program, just change the value of B, although b=a, but when changing the value of B, and then re-established an address, which is independent of a, so when changing the B value, and a is irrelevant, which is a bit like a pointer in C

Let's look at one more example

Example two:

var a={     name:' Hello '          }; var b=a;b.name= ' Hi '; alert (a.name); // of course, the result must be hi.

How to solve the above problem?

var a={     name:' Hello '          }; function copy () {    var b={};      for (var in a) {        b[attr]=a[attr]    }       return  b  }b.name= ' Hi '// Then the result is hello.        

The above method is called a shallow copy , using a for in to copy a property to B, but just copy a copy, in fact, when modifying the value of B does not change the value of a. Of course, a shallow copy has a deep copy.

 var  a={name:  ' {value: ' World '} ' Span style= "color: #000000;" >}  function   copy () { var  b={};  for  (var  attr in   a) {b[attr]  =a[attr];  return   b}b.name.value  = ' space ' ;alert (A.name.value);  //  

At this time people may or wonder, with a copy of how the result or space it! Because there is another value in JSON: ' World ' This type is an object, you copy it or object, or object reference, so the result is space, of course, may say that it will be used again copy on the line. The copy is called again by the result, which is the meaning of recursion, and the function itself is called inside the function. A little modification of the program can

varA={name:' {value: ' World '} '          }functiondeepcopy () {if(typeof a!= ' object '){        returnA}varb={};  for(varattrincha) {B[attr]=deepcopy (a[attr]); }       returnb}b.name.value= ' Space '; alert (a.name.value);//The result of this is world

There are two places to change, 1, the function of the internal call function itself B[attr]=deepcopy (a[attr]) 2, the terminating condition typeof a!= ' object ' is like above, you use a shallow copy of the object, the termination condition is that the detection type is not an object, Returns the value of a. This solves the problem. The above method is a deep copy .

Example three:

Now understand the shallow/deep copy, want to use HTML5 method to solve. Before we solve it, it is necessary to understand how to convert a string to a JS statement before HTML5, as follows:

var str= ' function task () {alert (' Hello ')} 'var fn=//Hello

HTML5 How to convert a JSON-formatted string into a JSON object , using Json.parse () as follows:

var a= '{  ' name ': ' Hello ';  }; ' var json=//Hello

This name adds "No" to the strict Json,json.parse method requirements must be strict JSON

How to turn a JSON object into a JSON-formatted string , using Json.stringify () as follows:

var a={   name:' Hello '  }; var json=//  ' {' name ': ' Hello '} '
The result is ' {' name ': ' Hello '} ', which is why you need to use a strict JSON format.

So how to solve the problem with HTML5, then the JSON into a string, and then the JSON format of the character into the object, the internship referred to a copy, and did not really reference a. And this is the copy.
The copy principle is the same. As follows:
var a={    name:' Hello '  }; var str=json.stringify (a); var obj=json.parse (str); var b=obj;b.name= ' Hi '; alert (a.name); // Hello
Expand:

This method is actually incompatible under 8, how to be compatible, is to refer to a JSON file: Json2.js, as follows

<script type= ' text/javascript ' src= ' json2.js ' ></script>

Solving the reference problem of JS object with shallow/deep copy, and HTML5 method

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.