[英]How to insert a for loop in the middle of an if/else if/else statement?
So I have to handle some wrong input in my game, so I wrote this while loop. 所以我必须在游戏中处理一些错误的输入,因此我编写了这个while循环。 The first if statement checks if the player asks himself, and the else if checks if a player asks a player that doesn't exist, if none of the above are true then it exits the while loop.
第一个if语句检查玩家是否自问,否则if检查玩家是否问不存在的玩家,如果以上都不是,则退出while循环。
Now, I need to do the second else if with a for loop that takes the variable playerNum as the number of times to run the loop, playerNum is the number of players that are playing. 现在,如果要使用一个以变量playerNum作为运行循环次数的for循环,我需要执行第二步,playerNum是正在播放的玩家数。 I'm not sure on how to structure this so that it works, because the for loop breaks up the if/else if/else statement so that else doesn't work.
我不确定如何构造它以便工作,因为for循环破坏了if / else if / else语句,从而使else无法正常工作。 Any ideas?
有任何想法吗?
EDIT : Is it possible to combine the first if with the else if statement as well? 编辑 :是否可以将第一个if以及else if语句组合在一起?
var wrongPlayer = true;
var player = askPlayer(); //Prompt to get a player to ask
while (wrongPlayer) { //Run as long as the player input is wrong
if (player === playerArray[turn].name) { //Player asks himself
player = askPlayer(); //Prompt again
}
else if (player != playerArray[0].name) { //Need to do this with a loop instead
player = askPlayer(); //depending on how many players there are
} //I have the player count stored in playerNum
else {
wrongPlayer = false; //Jump out of the loop
}
}
You should validate in the askPlayer
function, then it can just recurse rather than you calling it a bunch of times in a loop. 您应该在
askPlayer
函数中进行验证,然后它可以递归而不是您在循环中多次调用它。 Or you could make a validation function that is mutually recursive with askPlayer
. 或者,您可以使验证函数与
askPlayer
相互递归。 Either is better than what you had. 两者都比您拥有的要好。
var playerArray = []; //populate however
var NUMBER_OF_PLAYERS = playerArray.length;
var i = NUMBER_OF_PLAYERS;
function askPlayer(player) {
var askedPlayer = prompt(player + ', which player do you want to ask?');
if (askedPlayer == player ||
playerArray.indexOf(askedPlayer) == -1) {
alert('Not a valid player to ask');
askedPlayer = askPlayer(); //calls self here
}
return askedPlayer;
}
while (i--) {
var playerAsked = askPlayer(playerArray[i]);
//do whatever here for the turn logic
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.