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

前端 未结 4 2038
南笙
南笙 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:08

    In the first case you are doing a new memory allocation while you are actually modifying the array in the second case.

    Hence in the first case the value does not get modified.

    For eg:

    var myArrayOne = [2, 3, 4, 5];
    function doStuff(arr) {
      arr = [7,8,9]; //assigining a whole new object to the copy 
    }
    doStuff(myArrayOne);
    console.log(myArrayOne); // [2,3,4,5]
    
    // Scenario 2
    var myArrayTwo = [2, 3, 4, 5];
    function doStuff(arr) {
      arr.pop(); //modifying the internals of the arr object
    }
    doStuff(myArrayTwo);
    console.log(myArrayTwo); // [2,3,4]

提交回复
热议问题