Home  >  Q&A  >  body text

Difference between allocation and unpacking of arrays

<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>
P粉287254588P粉287254588434 days ago419

reply all(1)I'll reply

  • P粉187160883

    P粉1871608832023-08-14 11:43:19

    They are different.

    const arr2 = [...arr1]; // Line A
    

    LINE A, copy (shallow copy) each element of the array to arr2.

    const arr2 = arr1;      // Line B
    

    LINE B, assign the reference of arr1 to arr2. Basically, arr1 and arr2 are the same array.

    Example

    const arr = [1, 2, 3];
    
    const arrA = [...arr];
    const arrB = arr;
    
    console.log(arr === arrA); // False
    console.log(arr === arrB); // True
    
    arrA[0] = 9;
    console.log(arr[0] === arrA[0]); // False
    console.log(arr); // [1,2,3]
    console.log(arrA); // [9,2,3]
    
    arrB[0] = 9;
    console.log(arr[0] === arrB[0]); // True
    console.log(arr); // [9,2,3]
    console.log(arrB); // [9,2,3]
    

    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:

    const arr = [1, 2, [5, 6]];
    
    const arrA = [...arr];
    const arrB = arr;
    
    console.log(arr === arrA); // False
    console.log(arr === arrB); // True
    
    arrA[0] = 8;
    arrA[2][0] = 9;
    console.log(arr[2][0] === arrA[2][0]); // True
    console.log(arr); // [1, 2, [9, 6]]
    console.log(arrA); // [8, 2, [9, 6]]
    
    arrB[0] = 8;
    arrB[2][0] = 9;
    console.log(arr[2][0] === arrB[2][0]); // True
    console.log(arr); // [8, 2, [9, 6]]
    console.log(arrB); // [8, 2, [9, 6]]
    

    reply
    0
  • Cancelreply