[英]How to insert an array to another array at each iteration of a for loop in javascript
I have a function to bubble sort and I want to save the array after each swap into another array.我有一个 function 进行冒泡排序,我想在每次交换到另一个数组后保存数组。 The bubble sort is working properly and I can log the array after each swap to the console.
冒泡排序工作正常,我可以在每次交换到控制台后记录数组。 But I cant seem to push to the other array properly.
但我似乎无法正确推送到另一个阵列。
Here's my code:这是我的代码:
var arr = [5, 4, 3, 2, 1]; var steps = []; function bubbleSort() { for (let i = 0; i < arr.length - 1; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } var temp = arr; console.log(temp); steps.push(temp); } } console.log(steps); } const swap = (a, x, y) => { var temp = a[x]; a[x] = a[y]; a[y] = temp; }; bubbleSort();
Here's a screenshot of the console:这是控制台的屏幕截图:
It's only when I try to use get a hold of the array at each step that it isn't showing properly?只有当我尝试在每个步骤中使用获取数组时,它才能正确显示? what do I do?
我该怎么办?
I think clonning the array could work?我认为克隆阵列可以工作吗? var temp = [...arr];
var temp = [...arr];
var arr = [5, 4, 3, 2, 1]; var steps = []; function bubbleSort() { for (let i = 0; i < arr.length - 1; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } var temp = [...arr]; console.log(temp); steps.push(temp); } } console.log(steps); } const swap = (a, x, y) => { var temp = a[x]; a[x] = a[y]; a[y] = temp; }; bubbleSort();
You are inserting the Reference of the Temp-Array and not the actual content.您正在插入 Temp-Array 的引用而不是实际内容。 This way, you store multiple times the reference and at the End you are presented with all those reference pointing to the last version of your temp Array.
这样,您可以多次存储引用,并在最后向您展示所有这些引用,这些引用指向您的临时数组的最后一个版本。
You can use the destructuring assignment of an array, to create an easy shallow copy to be stored.您可以使用数组的解构赋值来创建一个简单的浅拷贝来存储。
var arr = [5, 4, 3, 2, 1]; var steps = []; function bubbleSort() { for (let i = 0; i < arr.length - 1; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } var temp = arr; console.log(temp); // Changed to destructuring assignment steps.push([...temp]) } } console.log(steps); } const swap = (a, x, y) => { var temp = a[x]; a[x] = a[y]; a[y] = temp; }; bubbleSort();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.