Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
临时变量未存储在Javascript中_Javascript_Arrays_Sorting_Selection Sort - Fatal编程技术网

临时变量未存储在Javascript中

临时变量未存储在Javascript中,javascript,arrays,sorting,selection-sort,Javascript,Arrays,Sorting,Selection Sort,我正在建立一个排序算法(选择排序),并已经能够完成它。但是,如果我想添加一个临时变量来存储未排序的数组,它似乎会立即更改为排序数组: 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]) { tem

我正在建立一个排序算法(选择排序),并已经能够完成它。但是,如果我想添加一个临时变量来存储未排序的数组,它似乎会立即更改为排序数组:

 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);
var A=[-8,1,77,99,3,5];
函数findMin(A、startIndex、endIndex){
var temp=startIndex;
对于(var x=startIndex;x A[x]){
温度=x;
}
}
返回温度;
}
函数交换号(A、index1、index2){
var temp_2=A[index1];
A[index1]=A[index2];
A[index2]=温度2;
返回A;
}
函数排序(A){
var endofArray=A.长度-1;
var temp3=A;
var Asorted=[];
对于(变量i=0;i
console.log中的
temp3
(“未排序的数组为“+”[“+temp3+”])” +“+”排序的数组是“+”[“+Asorted+”]“+”)似乎输出:

未排序的数组为[-99,-8,1,3,5,77]。排序后的数组为[-99,-8,1,3,5,77]。

而不是:

未排序的数组是[-8,1,77,-99,3,5]。排序后的数组为[-99,-8,1,3,5,77]。

请告诉我我的错误。
`

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

var temp3 = A.slice();