[英]How to run a program forever?
I've got got a stupid question, can you help me please? 我有一个愚蠢的问题,你能帮我吗? I want this program to run and run and run.
我希望该程序能够运行并运行。 At this moment after each try I have to refresh page to play again and it sucks.
在每次尝试之后的这一刻,我必须刷新页面才能再次播放,这很糟糕。
"8. Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number. If the user input matches with guess number, the program will display a message "Good Work" otherwise display a message "Not matched"." “ 8.编写一个JavaScript程序,该程序取1到10之间的一个随机整数,然后提示用户输入一个猜测数字。如果用户输入与猜测数字匹配,则程序将显示一条消息“ Good Work”,否则显示消息“不匹配”。
Here's what I've got: 这是我得到的:
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Looser! The number was " + randomNumber);
};
Put it in an endless loop: 将其无限循环:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
but , I wouldn't do that. 但是 ,我不会那样做。 I'd offer a way to get out:
我将提供一种出走的方法:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (!guessNumber) { // ***
break; // ***
} // ***
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
If the user presses Esc at the prompt
, guessNumber
will be ""
or null
(depending on the browser), both of which are falsy, so you'll break out of the loop. 如果用户在
prompt
按Esc ,则guessNumber
将为""
或为null
(取决于浏览器),两者都是虚假的,因此您将跳出循环。
Side note: "Loser" has only one "o" in it, and control-flow statements with attached blocks don't have ;
旁注:“失败者”中只有一个“ o”,带有附加块的控制流语句没有
;
after the block. 在块之后。
将所有代码放入while (true)
循环中。
just make an infinite loop 只是无限循环
var run = true
while (run)
{
console.log('foobar');
}
never set run as false and your loop will never stop 永远不要将run设置为false并且循环永远不会停止
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.