javascript - 为什么这个函数会改变数据?

标签 javascript immutability mutable

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 ]。

我期望的是: [ 1, 4, 3, 2 ] [ 1, 2, 3, 4 ]。

我想知道的是,为什么这会改变 asdf 变量? bubbleSort 函数获取给定数组 (asdf),复制它(排序),然后处理该变量并返回它,asd 设置为等于。我觉得自己像个白痴,但我不知道为什么会这样:(

最佳答案

The bubbleSort function takes the given array (asdf), makes a copy of it (sort)

不,它没有。赋值不会复制一个对象,它会创建另一个对现有对象的引用。

复制数组的一种简单方法是使用 Array.prototype.slice :

  let sort = toSort.slice( 0 );

有关复制对象的更多信息,请参阅:How do I correctly clone a JavaScript object?

关于javascript - 为什么这个函数会改变数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255297/

相关文章:

javascript - 无法正确显示悬停时导航下拉列表中的所有数据

javascript - JS - 通过按钮将 div 的可见性设置为隐藏

javascript - 如何在React中使用可变高度元素实现无限滚动?

javascript - 使用 ng new 命令创建 JavaScript 文件而不是 TypeScript

python - 创建一个 python 集合/唯一列表

java - 不可变/多态 POJO <-> 使用 Jackson 进行 JSON 序列化

java - Java 中的 String 对象不是不可变的吗?

python - QueryDict 列表未修改

arrays - 从 Scala 中的 for 循环生成 ArrayBuffer(或其他可变 Collection 类型)

python - open(file, "wt"或 "rt") 是不同的对象吗?