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