2013-03-17 85 views
0

我有這段代碼,我不知道爲什麼變量的值發生了變化。全局變量的值發生了變化,javascript

while (increment > 0) { 
     for (i = increment; i < n; i++) { 
      var unsorted = list; 
      console.log(unsorted + " -> unsorted" + i); 
      var temp = list[i]; 
      var j = i; 
      while (j >= increment && list[j - increment] > temp) { 
       list[j] = list[j - increment]; 
       j -= increment; 
      } 
      list[j] = temp; 
      console.log(unsorted + " -> must not change" + i); 
      console.log(list + "-> must not be the same below"); 
     } 
} 

當我再次登錄變量unsorted時,這些值已被更改?爲什麼?

回答

5

你只有一個數組。

var unsorted = list創建第二個參考,指向相同的數組實例。

取而代之,您可以調用list.slice(),它返回數組的一個(淺)副本。