排序数组的错误

时间:2016-11-12 21:26:17

标签: javascript arrays function sorting

我试图对id =" demo"的内容进行排序。用一个按钮,但每次我点击我的按钮我什么也得不到。

点击按钮后,我希望select()能够读取id =" demo"的内容。 (一旦输出随机数)并将它们排序/转储到id =" demo2"。

我认为正在发生的是select()将var arr读取为空数组,而不是具有随机数字分组的数组(因为它位于first()的末尾)

<input id="input1" type="number" min="10" max="100" onchange="first(); sortButton();">

<p id="demo"></p>

<!-- button appears here, once a value is entered into the input field -->
<p id="buttons1" onclick="select();"></p>


<p id="demo2"></p>

<script>


// once input1 value changes this outputs a random value less than N (value of input1) N times, then dumps out the random numbers in id="demo"

function first() {
var N = document.getElementById("input1").value;
var arr = []; 
while(arr.length < N)

{var randomnumber = Math.ceil(Math.random()*N);
arr[arr.length] = randomnumber;}
document.getElementById("demo").innerHTML = arr;}


// Once input1 value changes, this buttons appears in id="buttons"
function sortButton() {document.getElementById("buttons1").innerHTML =
'<button type="button" onclick="select();">Select Sort</button>';}



// meant to sort the random numbers in id="demo" once the button is clicked
function select() { 
document.getElementById("demo2").innerHTML = arr.sort(function(a,b){return a - b});}




</script>

1 个答案:

答案 0 :(得分:0)

你必须在你的函数之外声明var arr = []。这是一个有效的计划。希望它有所帮助:)

// once input1 value changes this outputs a random value less than N (value of input1) N times, then dumps out the random numbers in id="demo"
var arr = [];

function first() {
var N = document.getElementById("input1").value; 
while(arr.length < N){

  var randomnumber = Math.ceil(Math.random()*N);
  arr[arr.length] = randomnumber;
}
document.getElementById("demo").innerHTML = arr;
}


// Once input1 value changes, this buttons appears in id="buttons"
function sortButton() {
  document.getElementById("buttons1").innerHTML =
'<button type="button" onclick="select();">Select Sort</button>';
}



// meant to sort the random numbers in id="demo" once the button is clicked
function select() { 
document.getElementById("demo2").innerHTML = arr.sort(function(a,b){return a - b});
}
<input id="input1" type="number" min="10" max="100" onchange="first(); sortButton();">

<p id="demo"></p>

<!-- button appears here, once a value is entered into the input field -->
<p id="buttons1" onclick="select();"></p>


<p id="demo2"></p>