如何在if / else if / else语句的中间插入for循环?

时间:2014-10-13 16:05:16

标签: javascript

所以我必须在游戏中处理一些错误的输入,所以我在循环中编写了这个。第一个if语句检查玩家是否自问,而else检查玩家是否询问玩家是否存在,如果上述情况均不存在,则退出while循环。

现在,如果使用for循环将变量playerNum作为运行循环的次数,我需要执行第二个其他操作,playerNum是正在播放的玩家数量。我不确定如何构造它以便它起作用,因为for循环打破了if / else if / else语句,所以其他方法不起作用。有什么想法吗?

编辑:是否可以将第一个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
        }
    }

1 个答案:

答案 0 :(得分:0)

你应该在askPlayer函数中验证,然后它可以只是递归而不是你在循环中多次调用它。或者您可以创建一个与askPlayer相互递归的验证函数。要么比你拥有的更好。

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
}