javascript - 为什么 console.log(array) 给出的结果与 console.log({array}) 不同?

标签 javascript arrays object console.log

在实现冒泡排序算法时,我注意到将数组记录在对象内会产生与直接记录不同的结果。为什么?

function bubbleSort(arr) {
  let array = [...arr];
  let sorted = false;
  let round = 0;

  while (!sorted) {

    sorted = true;
    console.log({ array }); // this shows the already sorted array
    console.log(array); // this shows the array after one round of sorting

    for (let i = 0; i < array.length - 1 - round; i++) {
      if (array[i] > array[i + 1]) {
        [array[i], array[i + 1]] = [array[i + 1], array[i]];
        sorted = false;
      }
    }
    round++;
  }
  return array;
}

bubbleSort([1,4,6,3,45,78,9])

最佳答案

您的声明无效。

此代码显示 console.log 每轮都打印相同的数组。

function bubbleSort(arr) {
  let array = [...arr];
  let sorted = false;
  let round = 0;

  while (!sorted) {

    sorted = true;
    console.log({ array }, `Round no. ${round}`); // this shows the already sorted array
    console.log(array, `Round no. ${round}`); // this shows the array after one round of sorting

    for (let i = 0; i < array.length - 1 - round; i++) {
      if (array[i] > array[i + 1]) {
        [array[i], array[i + 1]] = [array[i + 1], array[i]];
        sorted = false;
      }
    }
    round++;
  }
  return array;
}

bubbleSort([10,7,15,1]);

这是我执行此代码片段时得到的结果

{
  "array": [
    10,
    7,
    15,
    1
  ]
} Round no. 0
[
  10,
  7,
  15,
  1
] Round no. 0
{
  "array": [
    7,
    10,
    1,
    15
  ]
} Round no. 1
[
  7,
  10,
  1,
  15
] Round no. 1
{
  "array": [
    7,
    1,
    10,
    15
  ]
} Round no. 2
[
  7,
  1,
  10,
  15
] Round no. 2
{
  "array": [
    1,
    7,
    10,
    15
  ]
} Round no. 3
[
  1,
  7,
  10,
  15
] Round no. 3

PS:如果你的意思是在 Chrome 控制台(或类似的东西)中打开它,它看起来像这样 console那么这取决于该控制台的实现。

array{ array } 的值都是内存中数组值持久保存的位置。这些值正在发生变化,因此,如果它没有保留您记录数组时的值,而只是保留内存段的值,那么当您展开它时,它会显示当前值,而不是历史值。

关于javascript - 为什么 console.log(array) 给出的结果与 console.log({array}) 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58781312/

相关文章:

将数组的拼接分配给自身时,Javascript 控制台打印不起作用

c - C中n数组的交集和并集

javascript - 如何遍历复杂的 Json 对象并对每个等于特定值的属性做一些事情

javascript - 为什么 React 钩子(Hook)在 React 文档中使用 const?

javascript - 如何在Reactjs中使用if else条件

javascript - jasmine describe函数中的beforeEach和afterEach自动添加代码

python - 如何平衡 numpy 数组中的类?

c++ - 预期类型得到 Element c++

php聚合对象,需要解释

javascript - 有没有更好的方法来编写这些函数?