Why do some operations not alter an array that was passed to a function?

前端 未结 4 2039
南笙
南笙 2021-01-20 02:31

Scenario 1:

var myArray = [2, 3, 4, 5];
function doStuff(arr) {
  arr = [];
}
doStuff(myArray);
console.log(myArray); // [2,3,4,5]
         


        
4条回答
  •  一生所求
    2021-01-20 03:09

    In the first example:

    You are altering the variable arr which is merely just holding a reference to the array [2, 3, 4, 5], so instead of holding a reference to [2, 3, 4, 5], it will hold a reference to another array [].

    At the line var myArray = [2, 3, 4, 5];:

    myArray -----------------------------------> [2, 3, 4, 5]
    

    Then at the line doStuff(myArray);:

    myArray -----------------------------------> [2, 3, 4, 5]
                                                      ↑
    arr ----------------------------------------------/
    

    Then at the line arr = [];:

    myArray -----------------------------------> [2, 3, 4, 5]
    
    arr ---------------------------------------> []
    

    => So, after the call to doStuff, myArray is still [2, 3, 4, 5].

    In the second example:

    You are using the reference to [2, 3, 4, 5] stored in arr to call a function pop on it that alters it.

    At the line var myArray = [2, 3, 4, 5];:

    myArray -----------------------------------> [2, 3, 4, 5]
    

    Then at the line doStuff(myArray);:

    myArray -----------------------------------> [2, 3, 4, 5]
                                                      ↑
    arr ----------------------------------------------/
    

    Then at the line arr.pop();:

    myArray -----------------------------------> [2, 3, 4, 5].pop()
                                                      ↑
    arr.pop() ----------------------------------------/
    

    Which alters the array to:

    myArray -----------------------------------> [2, 3, 4]
                                                      ↑
    arr ----------------------------------------------/
    

    => So, after the call to doStuff, myArray is now [2, 3, 4].

提交回复
热议问题