2017-02-27 34 views
0

我之前问过类似的问题,但我不清楚,我正在学习如何在这里提出正确的问题。我正在提示用户输入一个数组的大小,然后循环,让他们用数字填充数组,直到达到他们之前声明的大小。我的问题是如何正确地存储数组与用户的输入。提示时存储数组

function getNumber() { 

     var el = document.getElementById("demo"); 

     // Get the user's input and convert it to a number 
     var size = parseInt(prompt("Please enter the size of the array"),10); 


     var entries = parseInt(prompt("Enter an integer"),10); 

     var userInput = new Array(); 
     while (entries < size){ 
      var entries = parseInt(prompt("Enter an integer"),10); 
      userInput.push(entries); 
      userInput = entries.split(" "); 

     } 

     // Store the user's input to our global variable 
     //userInput[] = entries; 

     // Set up a string that will become the output. 

     //display iterations 
     el.textContent = userInput[entries]; 

    } 
+1

你重挫userInput阵列这里'userInput = entries.split(”“);' –

+1

这里:'userInput = entries.split( “”);'你覆盖你的'userInput'值。 –

+1

如果用户输入大小“3”,然后决定输入数字“3”,那么只要用户输入小于3的数字,循环就会结束! –

回答

2

我会写的代码稍有不同:

function getNumber() { 

    var el = document.getElementById("demo"); 

    // Get the user's input and convert it to a number 
    var size = parseInt(prompt("Please enter the size of the array"),10); 

    // array that will store user input 
    var userInput = []; 
    while (userInput.length < size){ 
     var entries = parseInt(prompt("Enter an integer"),10); 
     userInput.push(entries) 
    } 
    //join array element with a space to display 
    el.textContent = userInput.join(" "); 

} 
+0

啊,我看到我出错了,谢谢你的帮助。 –