Why does this function mutate data?

三世轮回 提交于 2019-12-11 06:18:54

问题


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);

The output to this code is: [ 1, 2, 3, 4 ] [ 1, 2, 3, 4 ].

What I would expect:         [ 1, 4, 3, 2 ] [ 1, 2, 3, 4 ].

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 :(


回答1:


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.

A simple way to copy an array is to use Array.prototype.slice:

  let sort = toSort.slice( 0 );

For more on copying objects in general see: How do I correctly clone a JavaScript object?




回答2:


You are sorting the input list given as a function argument which is mutable. When you assign the list to a new variable, it doesn't create a 'copy' it just creates another reference pointing to the same list, same data, which you then go ahead a sort. This is why both asdf and add variables are the same, because they are two variables that point to the same memory location, same data.

If you wish to copy the array so not to modify the input array, have a look into the javascript slice() method.




回答3:


You need to clone the original array to avoid the change happening in original array. clone can be done by using

  1. slice() prototype method.
  2. loop.
  3. Array.from().
  4. concat().

Replace let sort = toSort; with let sort = toSort.slice(0); or

 let sort=[];
  for(var i=0;i < toSort.length;i++){
  sort[i]=toSort[i];  
  }

or

  let sort = Array.from(toSort);

or

let sort = toSort.concat();

function bubbleSort(toSort) {
  let sort = toSort.slice(0);
  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);


来源:https://stackoverflow.com/questions/41255297/why-does-this-function-mutate-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!