临时变量不存储在Javascript中

临时变量不存储在Javascript中

问题描述:

我正在构建一个排序算法(选择排序),并且已经能够完成它。但是,如果我想添加一个临时变量,它存储了排序的数组,它似乎是马上改口数组排序:临时变量不存储在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我的错误。 `

+0

http://*.com/questions/7486085/copying-array-by-value-in-javascript –

将temp3分配给A时,基本上只是指向内存中的A数组,而不是实际上复制数组。尝试:

var temp3 = A.slice(); 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice