为什么此功能会变异数据? [英] Why does this function mutate data?
问题描述
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);
此代码的输出为:[1,2,3,4] [1,2,3,4].
The output to this code is: [ 1, 2, 3, 4 ] [ 1, 2, 3, 4 ].
我期望的是: [1,4,3,2] [1,2,3,4].
What I would expect: [ 1, 4, 3, 2 ] [ 1, 2, 3, 4 ].
我想知道的是为什么这会使asdf变量突变? bubbleSort函数采用给定的数组(asdf),对其进行复制(排序),然后处理该变量并将其返回,并将其asd设置为等于.我觉得自己是个白痴,但我不知道为什么这是:(
What I'm wondering, is why does this mutate the asdf variable? The bubbleSort function takes the given array (asdf), makes a copy of it (sort), and then deals with that variable and returns it, which asd is set equal to. I feel like an idiot but I have no clue why this is :(
推荐答案
bubbleSort函数采用给定的数组(asdf),对其进行复制(排序)
The bubbleSort function takes the given array (asdf), makes a copy of it (sort)
不,不是.分配不会复制对象,它会创建对现有对象的另一个引用.
No, it doesn't. Assignment doesn't make a copy of an object, it creates another reference to an existing object.
复制数组的一种简单方法是使用 Array.prototype.slice :
A simple way to copy an array is to use Array.prototype.slice:
let sort = toSort.slice( 0 );
有关一般复制对象的更多信息,请参见:如何正确进行克隆一个JavaScript对象?
For more on copying objects in general see: How do I correctly clone a JavaScript object?
这篇关于为什么此功能会变异数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!