在Javascript中我们知道给一个函数传递一个数组做为实参,这是按引用传递的,但如果在这个函数里面覆盖这个引用,那么会有什么结果呢?请看下面的代码:
+ 展开代码查看源码打印?·········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'; //改变数组的某个元素是可以的
05.
print(oldArray + ' in modifyArray1');
06.}
07.
08.modifyArray1(oldArray);
09.print(oldArray + ' out modifyArray1');
10.
11.print('==========================================');
12.
13.oldArray = [1, 2, 3]; //复原数组
14.
15.function modifyArray2(oldArray) {
16.
var newArray = ['a', 'b', 'c'];
17.
oldArray[0] = 'test2'; //对数组元素的更改是有效的
18.
oldArray = newArray; //覆盖引用,一旦出了函数的作用域就是无效的
19.
print(oldArray + ' in modifyArray2');
20.}
21.
22.modifyArray2(oldArray);
23.print(oldArray + ' out modifyArray2');
可以通过JavaScript shell来执行这段代码。我的输出结果为:
+ 展开代码查看源码打印?·········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
这就说明了一个事实:在一个函数里如果直接覆盖实际参数的引用,在函数内部是有效的,但出了函数作用域就会失效。