Today when watching react-native performance optimization, see how to avoid shouldcomponentupdate abnormal data, a storm in the brain, thus implicated a series of problems, So there is this article about the JS array copy (deep copy) and assignment and so on why can produce abnormal data.
What's the problem, please?
Now get to the point:
First, the exception data is generated when we copy the assignment, there will be or not change to its own value.
First, push and concat
Push is defined as adding one or more elements to the end of the array and returning the new length. The method changes the length of the array.
CONCAT is defined as connecting two or more arrays and returning the result, which does not alter the existing array, but only returns a copy of the array.
var a = [+]; A.push ([3,4]); A.concat (5); //
Second, deep copy and shallow copy
1. Shallow copy
JavaScript storage objects are stored addresses, so shallow copy causes A and B to point to the same memory address
The assignment of an array is actually equivalent to the index, and changing one of the variables will change the other reference.
var a = [N/a ]; var b = A; b[0] = 4; // A is 4 2 3 // B is 4 2 3
Depending on the problem with the storage object above, another problem can be resolved here:
The original parameter (such as a specific number) is passed as a value to the function, and the value is passed to the function, and if the called function changes the value of the parameter, the change does not affect the global or call function.
You pass an object (in JS, the array is not a simple data type, but an object) to a function, and if the contents of this parameter are changed inside the function, the change is visible outside.
2. Deep copy
(1) Slice function
(2) Concat function
(3) Assgin
The principle of three functions is to return a copy of the array (equivalent to another memory space), so it does not change the value of the array itself
But here's a little different, that's the difference between Assgin and the other two points.
Although Assgin is also a deep copy, he is only a deep copy of the first layer, followed by a shallow copy after the second layer, examples are as follows:
var a = { a1:{ Aa1:' One ', aa2: ' $' } } var b = Object.assgin ({},a); var c = object.assgin ({},a); =; /* b:{ a1:{ aa1: ' $ ', AA2: ' $ ' } c:{a1:{aa1 : ' ", Aa2 : ' A ' } } * /
Copy assignment of JS array two or three summary