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

前端 未结 4 2085
南笙
南笙 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 02:58

    arr is a reference to the array, which exists somewhere in memory (you don't know where, and you don't care). When you say arr = [], you're creating a new array somewhere in memory, and changing arr to refer to that new array. The old array still exists in memory. If there was nothing referring to the old array then it would eventually be garbage collected, but in this case it's still referred to by myArray so it remains untouched.

    arr.pop() on the other hand is modifying the array, not changing references.

提交回复
热议问题