我尝试使用 javascript DOM 显示排序后的数组,但它只显示输入的数组。我做错了什么?
例如对于数组 到达[7,8,2,3,5,4] 当我在没有 Dom 的情况下单独运行 js 文件时,它显示 [2,3,4,5,7,8] 但使用 DOM 时 [7,8,2,3,5,4]
function BubbleSort(Arr){
var temp;
var Arr=document.getElementById("data1").value;
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]){
temp = Arr[j];
Arr[j] = Arr[j+1];
Arr[j+1] = temp;
}
}
}
console.log(Arr);
document.getElementById("demo").innerHTML="the answer is :" +Arr;
};
最佳答案
问题是您正在从 DOM 读取某些内容并将其作为数组传递。从“data1”读取值后,请确保它是一个数组,然后再将其传递给您的函数。
function BubbleSort() {
var temp;
var Arr = document.getElementById("data1").value;
// this next line will split the input if you're setting it as a string
Arr = Arr.split(',');
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]) {
temp = Arr[j];
Arr[j] = Arr[j + 1];
Arr[j + 1] = temp;
}
}
}
console.log(Arr);
document.getElementById("demo").innerHTML = "the answer is :" + Arr;
}
BubbleSort();
<input type="text" id="data1"></input>
<div id="demo"></div>
<button onclick="BubbleSort()">Sort</button>
关于javascript - 如何显示排序后的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54161049/