我正在尝试编写一个对数组执行操作并返回数组的不同副本并使原始副本保持不变的函数。我想我可以通过声明var array2 = array
然后进行数组操作来做到这一点。我究竟做错了什么?
这是我的示例函数:
var partition = function(array, p){
var pivot = array[p];
var length = array.length;
// make a copy and move pivot to the front
var array2 = array;
array2[p] = array2[0];
array2[0] = pivot;
// partition the array
var i = 1;
for (var j = 1; j < length; j++){
//console.log('i='+i+', j='+j)
if (array2[j] < pivot) {
var temp = array2[j];
array2[j] = array2[i];
array2[i] = temp;
i++;
}
}
//console.log('array after partitioning: ' + array)
// swap pivot
array2[0] = array2[i-1];
array2[i-1] = pivot;
var answer = {array: array2, p: i-1}
return answer;
};
我的示例电话:
var a = [3, 2, 1];
partition(a, 0);
console.log(a); // prints [1,2,3] but I want [3,2,1]