Difference between allocation and unpacking of arrays
P粉287254588
2023-08-13 16:31:45
<p>So I have this JavaScript code, what is the difference between Line A and Line B</p>
<pre class="brush:php;toolbar:false;">const arr1 = [1,2,3,4,5]
const arr2 = [...arr1]; // Line A
const arr2 = arr1; // Line B</pre>
<p>So I want to know whether these two assignment methods are the same or there are some differences</p>
They are different.
LINE A, copy (shallow copy) each element of the array to
arr2
.LINE B, assign the reference of
arr1
toarr2
. Basically,arr1
andarr2
are the same array.Example
Shallow copy
Shallow copy only copies the first level items. For example, if an array contains another array, the inner array is copied, but the elements of the inner array are not copied. Therefore, deep elements are not copied. See the code example below: