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

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

    In the first function, you're just reassigning the parameter of the function. That has no effect on the passed data.

    In the second, you're actually mutating the passed array via the call to pop.

    Think of it this way: in

    var a = 1
    a = 2
    

    Is the 1 modified in any way? No, the reference a that was pointing to it was just changed.

提交回复
热议问题