我目前正在用Javascript编写一个简单的程序。我无法弄清楚为什么程序无法正常工作。用户应该能够猜出一个数字,程序会告诉用户是否需要猜测更高或更低。现在,它甚至没有给我第一个提示。感谢您的帮助。
<html>
<head>
</head>
<body>
<script>
//Guessing Game
function guessingGame() {
var userNumber = prompt("Pick a number 1 through 1000!", "Type your number here");
var computerNumber = Math.floor(Math.random() * 1000 + 1);
var tries = 0;
var done = false;
while (done === false) {
if (userNumber < computerNumber) {
document.write("Your number was too low.");
tries = tries + 1;
userNumber = prompt("Please guess again", "Type your number here");
} else if (userNumber > computerNumber) {
document.write("Your number was too high.");
tries = tries + 1;
userNumber = prompt("Please guess again", "Type your number here");
} else {
document.write("Great Job!!! You guessed the number in " + tries + " tries!" );
done = true;
}
}
}
guessingGame();
</script>
</body>
</html>
答案 0 :(得分:2)
document.write("Great Job!!! You guessed the number in " + tries " tries!" );
此行在+
之后缺少tries
。语法错误通常会导致整个JavaScript块被丢弃,因此无法运行。
if (userNumber < computerNumber) {
您还应该避免在JavaScript代码中使用未转义的<
,因为它与HTML无法很好地混合。写下
if (userNumber < computerNumber) {
或put the entire script into a CDATA section允许使用未转义的尖括号。
<script>
// <![CDATA[
/* code here, can use '<' freely */
// ]]>
</script>
答案 1 :(得分:2)
您忘记了行中的其他连接+
:
document.write("Great Job!!! You guessed the number in " + tries " tries!" );
应该是
document.write("Great Job!!! You guessed the number in " + tries + " tries!" );
jsFiddle 上的固定示例。