我似乎無法理解,如果我將用戶的輸入分配給變量「手指」,爲什麼這會一直崩潰。我已經通過警報測試了代碼的每個部分,並且一切似乎都正常。我還發現,如果我爲腳本中的變量指定一個數字,它就可以正常工作。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>
你想達到什麼目的?爲了清楚起見,請解釋上下文。 –