2016-04-14 60 views
0

我似乎無法理解,如果我將用戶的輸入分配給變量「手指」,爲什麼這會一直崩潰。我已經通過警報測試了代碼的每個部分,並且一切似乎都正常。我還發現,如果我爲腳本中的變量指定一個數字,它就可以正常工作。Javascript:當用戶輸入分配變量時發生崩潰

我認爲這可能是輸入值被當作字符串讀取,因此在比較時決不會等於一個數字,並且會使腳本進入無限循環。所以我將輸入框指定爲type:number,並且它仍然崩潰。

想到任何人?

<html> 

     <head> 
      <title> How Many Fingers - Computer Guesser </title> 
     </head> 

     <body> 

      <h1> How many fingers? </h1> 

      <input id='fingersInput' type='number' min='1' max='10' placeholder="Insert the number of fingers here." /> 

      <button id='check'> Go! </button> 

      <hr> </hr> 
      <p id='computerGuessesOutput'> </p> 
      <p id='allguessesOutput'> </p> 

     <script type='text/javascript'> 

      document.getElementById('check').onclick = function() { 

       var fingers = document.getElementById('fingersInput').value; 

       //var fingers = 5; 

       var computerGuesses = Math.floor(Math.random() * 11); 

       var numberOfGuesses = 1; 

       var allguesses = [computerGuesses]; 

       while (fingers !== computerGuesses) { 
        computerGuesses = Math.floor(Math.random() * 11); 

        numberOfGuesses++; 

        allguesses.push(computerGuesses); 

         } 

       document.getElementById('computerGuessesOutput').innerHTML = numberOfGuesses; 
       document.getElementById('allguessesOutput').innerHTML = allguesses; 

      } 



     </script> 

     </body> 
    </html> 
+0

你想達到什麼目的?爲了清楚起見,請解釋上下文。 –

回答

1

當你比較使用!==,它不只是值進行比較,而是按類型,在這種情況下,手指是一個字符串,而computerGuesses是一個數字。

您既可以轉換成「手指」到第一個號碼,使用parseInt函數(),或使用比較!=

你可以看到這個更清晰地打印在控制檯類型。檢查了這一點:

document.getElementById('check').onclick = function() { 
 
    var fingers = document.getElementById('fingersInput').value; 
 
    var computerGuesses = Math.floor(Math.random() * 11); 
 
    var numberOfGuesses = 1; 
 
    var allguesses = [computerGuesses]; 
 
    console.log(fingers, computerGuesses); 
 
    console.log(typeof fingers, typeof computerGuesses); 
 

 
}
<html> 
 

 
    <head> 
 
    <title> How Many Fingers - Computer Guesser </title> 
 
    </head> 
 

 
    <body> 
 

 
    <h1> How many fingers? </h1> 
 

 
    <input id='fingersInput' type='number' min='1' max='10' placeholder="Insert the number of fingers here." /> 
 

 
    <button id='check'> Go! </button> 
 

 
    <hr> </hr> 
 
    <p id='computerGuessesOutput'></p> 
 
    <p id='allguessesOutput'></p> 
 
    </body> 
 
</html>

-1

首先,它是一個輸入,所以你會得到它的文字,就像你說的。 type屬性用於顯示和驗證,它始終是一個字符串, 因爲您需要一個數字,您應該執行parseInt將結果轉換爲整數。

然後,您不檢查您的手指值是否在隨機範圍內(在您的示例中爲1-11),因此任何超出此範圍的數字都將導致無限循環。