gpt4 book ai didi

javascript - for 循环的每次迭代输出一个数组

转载 作者:行者123 更新时间:2023-11-28 14:14:26 24 4
gpt4 key购买 nike

我有一个脚本,它接受用户输入的数字,将它们分配给一个数组,然后使用冒泡排序方法将这些数字按顺序排列。

一切都工作得很好,但我似乎无法弄清楚如何输出数组的内容,因为每次迭代都会更改数组的内容。基本上,我想在每个外部 for() 循环周期的新行上观察它的运行情况。

function sortFunction()
{
var totalNums = prompt("How many numbers would you like to enter?","");
var numsArray = [];

for(i=0; i<totalNums; ++i)
{

var nums = prompt("Please enter number " ,"");
if(nums != 'x')
{
numsArray[i] = parseInt(nums);
document.getElementById("unsorted").innerHTML = "Orignal Numbers: " + numsArray;

}
}

var length = numsArray.length;
var swapped;

do
{
swapped = false;
for (var j=0; j < length-1; j++)
{
if (numsArray[j] > numsArray[j+1])
{
var temp = numsArray[j];
numsArray[j] = numsArray[j+1];
numsArray[j+1] = temp;
swapped = true;

}
}
document.getElementById("sorted").innerHTML = (numsArray); //This is where I am needing help
} while (swapped);
}
<p> Click the button to enter and display an array of numbers! </p>
<button onclick="sortFunction()">Click Me</button>

<div id ="unsorted">Unsorted</div>
<div id ="sorted">Sorted</div>

最佳答案

你们非常接近。我所做的只是将innerHTML 行上的运算符更改为+= 而不是=。我还添加了一行来每次清除“已排序”队列,并对结果进行一些格式化。

function sortFunction() {
var totalNums = prompt("How many numbers would you like to enter?", "");
var numsArray = [];

document.getElementById("sorted").innerHTML = "";

for (i = 0; i < totalNums; ++i) {

var nums = prompt("Please enter number ", "");
if (nums != 'x') {
numsArray[i] = parseInt(nums);
document.getElementById("unsorted").innerHTML = "Orignal Numbers: " + numsArray;

}
}

var length = numsArray.length;
var swapped;
let x = 0;

do {
x++;
swapped = false;
for (var j = 0; j < length - 1; j++) {
if (numsArray[j] > numsArray[j + 1]) {
var temp = numsArray[j];
numsArray[j] = numsArray[j + 1];
numsArray[j + 1] = temp;
swapped = true;

}
}
document.getElementById("sorted").innerHTML += "Step " + x + ": " + (numsArray) + "<br>"; //This is where I am needing help
} while (swapped);
}
<p> Click the button to enter and display an array of numbers! </p>
<button onclick="sortFunction()">Click Me</button>
<div id="unsorted">Unsorted</div>
<div id="sorted">Sorted</div>

关于javascript - for 循环的每次迭代输出一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58152385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com