我似乎无法理解,如果我将用户输入分配给变量“fingers”,为什么这总是崩溃。我已经通过警报测试了代码的每个部分,并且一切似乎都正常进行。我还发现,如果我为脚本中的变量分配一个数字,则可以正常工作。
我以为输入值可能是作为字符串读取的,因此比较时永远不会等于数字,这使脚本陷入了无限循环。因此,我将输入框分配为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>
最佳答案
当使用!==比较时,它不仅按值比较,而且按类型比较,在这种情况下,finger是一个字符串,而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>
关于javascript - Javascript:由用户输入分配变量时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631187/