在实现冒泡排序算法时,我注意到将数组记录在对象内会产生与直接记录不同的结果。为什么?
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 控制台(或类似的东西)中打开它,它看起来像这样 那么这取决于该控制台的实现。
array
和 { array }
的值都是内存中数组值持久保存的位置。这些值正在发生变化,因此,如果它没有保留您记录数组时的值,而只是保留内存段的值,那么当您展开它时,它会显示当前值,而不是历史值。
关于javascript - 为什么 console.log(array) 给出的结果与 console.log({array}) 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58781312/