In Javascript, we know that passing an array as an actual parameter to a function is passed by reference, but if this reference is overwritten in this function, what will be the result? Please look at the code below:
+ Expand the code to view the source code and print?·········10········20········30·········40······ ··50·········60·········70·········80·········90·········100·· ·····110·······120·······130·······140·······150
01.var oldArray = [1, 2, 3];
02.
03.function modifyArray1(oldArray) {
04.
oldArray[0] = 'test1'; //It is possible to change an element of the array
05.
print(oldArray + ' in modifyArray1');
06.}
07.
08.modifyArray1(oldArray);
09.print(oldArray + ' out modifyArray1');
10.
11.print('==========================================');
12.
13.oldArray = [1, 2, 3]; //Restore the array
14.
15.function modifyArray2(oldArray) {
16.
var newArray = ['a', 'b', 'c'];
17.
oldArray[0] = 'test2'; //Changes to array elements are valid
18.
oldArray = newArray; //Overwrite the reference, it will be invalid once it goes out of the scope of the function
19.
print(oldArray + ' in modifyArray2');
20.}
twenty one.
22.modifyArray2(oldArray);
23.print(oldArray + ' out modifyArray2');
This code can be executed through the JavaScript shell. My output is:
+ Expand the code to view the source code to print?·········10·········20·········30········40 ·········50·········60·········70········80·········90····· ···100·······110·······120·······130········140·······150
1.test1,2,3 in modifyArray1
2.test1,2,3 out modifyArray1
3.==========================================
4.a,b,c in modifyArray2
5.test2,2,3 out modifyArray2
This illustrates the fact that if you directly overwrite the reference of the actual parameter in a function, it is valid inside the function, but it will become invalid outside the scope of the function.