[英]I can not seem to get a while loop to work with my code
当我像这样放入 while 循环时,我的背景和提示永远不会出现。 我不知道为什么会造成这种情况。 其他一切都完美无缺,只是一旦我添加了 while 循环,我的代码就中断了。 我也尝试过 for 循环,但它也不起作用。
//score
var score = 0
//replay loop
var replay = "yes"
//name of each gen 1 pokemon
var pname = ['#']
//images for each one
var bg = ['#']
while (replay == 'yes'){
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
setTimeout(() => {
var answer = prompt("What pokemon is this?")
if (answer.toLowerCase() == pname[num].toLowerCase()) {
alert("correct")
score ++
replay = prompt("Want to keep playing?")
} else {
alert("incorrect")
replay = prompt("Want to keep playing?")
}
}, 2000);
}
setTimeout function 在运行之前需要 2 秒,从而导致你的 while 循环在 2 秒内执行大量实际次数......一直在更新背景图像(它可能在 2 秒内轻松超过 10,000 X .
我建议使用递归:
//score
var score = 0;
//replay loop
var replay = "yes";
//name of each gen 1 pokemon
// var pname = [#]; <- this needs to hold all the available names
//images for each one
//var bg = [#]; <-this needs to hold all the available images
let keepPlaying = function(){
background = bg[Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
var answer = prompt("What pokemon is this?")
if (answer.toLowerCase == pname[num].toLowerCase) {
alert("correct")
score ++
replay = prompt("Want to keep playing?")
} else {
alert("incorrect")
replay = prompt("Want to keep playing?")
}
if(replay == 'yes')
keepPlaying()
else
return(score)
}()
while 循环不会等待 setTimeout() 完成。您需要找出不同的方法。
这两条线都无效
var pname = [#] // var pname = ['#']
var bg = [#], // var bg = ['#']
var score = 0 var replay = "yes" var pname = ['#'] var bg = ['#'] var index = 0; (function asyncLoop() { background = bg[num = Math.floor(Math.random() * bg.length)]; document.body.style.backgroundImage = 'url(' + background + ')'; setTimeout(function() { var answer = prompt("What pokemon is this?") if (answer == pname[num]) { alert("correct") score ++ replay = prompt("Want to keep playing?") } else { alert("incorrect") replay = prompt("Want to keep playing?") } if (replay == 'yes'){ asyncLoop(); } }, 1000); })();
<body></body>
让我先指出代码中的几件事。
var pname = [#] --> 语法无效
var bg = [#], --> 无效且此处有逗号
此外,setTimeOut function 被多次执行,因此使脚本无响应。
试试这个:
var pname = ['qq','ww','ee'];
var replay = "yes";
var score = 0;
var bg = [];
var num = 1;
keepPlaying();
function keepPlaying() {
var answer = prompt("What pokemon is this?")
if (answer == pname[num]) {
alert("correct")
score ++
replay = prompt("Want to keep playing?")
}
else {
alert("incorrect")
replay = prompt("Want to keep playing?")
}
if(replay == 'yes') {
keepPlaying();
}
else {
alert(score);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.