Questions about the JS copy object

Source: Internet
Author: User

When using Vue to meet a requirement needs to back up a multidimensional array of objects, using several methods to get the results are interrelated, can not be done on the basis of modifying the original array, copy out a copy of the original data for the change, see the next online the way the big fairy, or can not be convinced that, It's best to try it out for yourself.

The first is example 1, if it is a simple array object:

// ------------Situation 1------------    var arr = [0,1,2,3];         var arr1 = arr;     var arr2 = arr.slice (0);     var arr3 = json.parse (json.stringify (arr));    Arr.push (4);    Console.log (arr1);    Console.log (ARR2);    Console.log (ARR3);

The result is this:

Can be seen after both well satisfied with our needs, did not receive the impact.

Then there is the example 2, which is a relatively complex multidimensional object.

1 //------------situation 2------------2     varobj = [3{A: ' 0 '},4{b: ' 1 '},5{c: ' 2 '},6         { 7 d:[8{e: ' 3 '},9{f: ' 4 '},Ten{g: ' 5 '}, One             ] A         }, -     ]; -     varCopy1 =obj; the     varCopy2 = Obj.slice (0); -     varCopy3 =json.parse (json.stringify (obj)); -  -obj[3].d[2][' h '] = ' 6 '; + Console.log (copy1); - Console.log (copy2); +Console.log (COPY3);

Results

The result is different, found that the first two ways have changed, this is because slice (), contact () such a similar method can only be a simple copy of the array object, if it contains the object, it can not be willing to, or the third kind of firm;

Because, for JS, regardless of the array object, the JSON object, which itself is a reference type, is pointing to its address, the use of JSON parsing to a non-reference type of string variables, and then back to parse, so the result is satisfactory, of course, if it is like

PHP has a & quote symbol, so don't worry about it.

Questions about the JS copy object

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.