在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
這就說明了一個事實:在一個函數裡如果直接覆寫實際參數的引用,在函數內部是有效的,但出了函數作用域就會失效。