1 javascript mutable immutability
function bubbleSort(toSort) {
let sort = toSort;
let swapped = true;
while(swapped) {
swapped = false;
for(let i = 0; i < sort.length; i++) {
if(sort[i-1] > sort[i]) {
let temp = sort[i-1];
sort[i-1] = sort[i];
sort[i] = temp;
swapped = true;
}
}
}
return sort;
}
let asdf = [1,4,3,2];
let asd = bubbleSort(asdf);
console.log(asdf, asd);
Run Code Online (Sandbox Code Playgroud)
此代码的输出为:[1,2,3,4] [1,2,3,4].
我期待的是:[1,4,3,2] [1,2,3,4].
我想知道的是,为什么这会改变asdf变量?bubbleSort函数接受给定的数组(asdf),复制它(排序),然后处理该变量并返回它,asd设置为等于.我觉得自己像个白痴,但我不知道为什么会这样:(
bubbleSort函数接受给定的数组(asdf),制作它的副本(排序)
不,它没有.赋值不会创建对象的副本,它会创建对现有对象的另一个引用.
复制数组的一种简单方法是使用Array.prototype.slice:
let sort = toSort.slice( 0 );
Run Code Online (Sandbox Code Playgroud)
有关复制对象的更多信息,请参阅:如何正确克隆JavaScript对象?