Transfer of function input parameters

  Is JavaScript a pass-by-reference or pass-by-value language?  

Mar.09,2021

when calling the function change , change this function has a new variable arr in its scope. This arr and global arr both point to the same memory address , that is, the memory address of the storage array [1,2] .

Code snippet one executes arr = [1,2,3] , that is, stores a new array [1,2,3] in memory, and then assigns the memory address of this array to arr . Note that this arr is a variable in the change function, so this arr points to the array [1, 2, 3] < / /. The global arr still points to the memory address of [1,2] . Note that [1,2,3] is a new array, so a new memory space is required.

Code snippet 2 executes arr.push (3) , first finds the array pointed to by arr , that is, [1,2] , and then adds data 3 to this array, because arr and global arr in the change function point to the same memory address, and the content of this address has changed.


arr is equivalent to an address container "arr = [1,2,3]". It just puts the address of the new "[1,2,3]" array into the arr, overwriting the original address, and the original array still exists in the same place

.

var arr = [1,2]
generated two blocks of space
memory A: the instance that holds the array [1,2]
memory B: the address where "A" is stored is called "arr"

.

arr = [1,2,3]
generated a block of space
memory C: an instance of the array [1,2,3]
and changed the content of "B" from the address of "A" to the address of "C"

this assignment only affects the value of "B", not "A"

.

arr.push (3)
is through the contents of arr, that is, "B", to find "A" and put a value in it, which is really modified to the original array

. The

parameterized function actually has an implicit variable declaration, the first function, which changes the pointing address of the local variable. In the second function, the local variable points to the same address object as the global variable, so the result is different.

Menu