我正在構建一個排序算法(選擇排序),並且已經能夠完成它。但是,如果我想添加一個臨時變量,它存儲了排序的數組,它似乎是馬上改口數組排序:臨時變量不存儲在Javascript中
var A = [-8, 1, 77, -99, 3, 5];
function findMin(A,startIndex,endIndex) {
var temp = startIndex;
for(var x = startIndex; x <= endIndex; x++){
if(A[temp] > A[x]) {
temp = x;
}
}
return temp;
}
function swapNumbers(A, index1, index2) {
var temp_2 = A[index1];
A[index1] = A[index2];
A[index2] = temp_2;
return A;
}
function sort(A) {
var endofArray = A.length - 1;
var temp3 = A;
var Asorted = [];
for(var i = 0; i < A.length; i++) {
swapNumbers(A, i, findMin(A, i, endofArray));
}
Asorted = A;
console.log("The unsorted array was " + "[" + temp3 + "]"
+ "." + " The sorted array is " + "[" + Asorted + "]" + ".");
return Asorted; /*subsitute return for
console.log() to display results*/
}
sort(A);
在console.log("The unsorted array was " + "[" + temp3 + "]" + "." + " The sorted array is " + "[" + Asorted + "]" + ".");
的temp3
似乎輸出:
The unsorted array was [-99,-8,1,3,5,77]. The sorted array is [-99,-8,1,3,5,77].
:
The unsorted array was [-8, 1, 77, -99, 3, 5]. The sorted array is [-99,-8,1,3,5,77].
請INF orm我的錯誤。 `
http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript –