2017-02-27 25 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

啊,我看到我出錯了,謝謝你的幫助。 –