如果第一次给出正确的输入但是在重新提示后没有给出语句,则跳过语句?

时间:2014-10-12 10:47:15

标签: javascript

我遇到了一个被跳过的语句的问题,还有一个无限循环,我无法弄清楚为什么它是无限的,因为它似乎在正确的输入已经结束时结束给出。

这是一个小提琴,让您更容易理解发生的事情:http://jsfiddle.net/z03ffn2j/

在else语句中,我运行一个while循环,只要当前玩家试图在askPlayer函数中问自己问题就会运行。因此,如果一名球员被命名为"克里斯"并且该玩家进入" chris",提示再次出现。

一切都很好,但是..当我没有打字"克里斯"第一次,而是键入,让我们说" tommy",它会跳过要求值的var card语句。但是,当我进入"克里斯"第一次,它重新提示我自己,然后我进入" tommy",它不会跳过var code语句。所以我的问题是,当我第一次输入正确的名字时,为什么会跳过它,但是如果我先输入一个错误的名字然后输入一个正确的名字呢?

var playerArray = []; //Contains player objects
var turn = 0; //Keeps track of whose turn it is

function askPlayer() {
    var askedPlayer = prompt('Which player do you want to ask?');
    return askedPlayer;
}

//While the pairCount is less than 13(maximum possible pairs)
while (pairCount < maxPairs) {

    if (playerArray[turn].totalCards == 0) {
    drawCard(); 
    }

    else {
        var wrongInput = true;
        var player = askPlayer();

        while (wrongInput) {

            if (player === playerArray[turn].name) {
                player = askPlayer();
                if (player != playerArray[turn].name) {
                    wrongInput = false;    
                }
            }
        }

    var card = askCard(player); //<--- This statement gets skipped
}

pairCount = 13; //Prevents infinite loop for now
turn++;

if (turn == playerNum - 1) { //If everyone has made their turn, reset to player1 again
    turn = 0;
}

}

1 个答案:

答案 0 :(得分:1)

当您输入的玩家名称不等于当前回合的玩家名称时,您将进入无限循环。

你有:

var wrongInput = true;
var player = askPlayer();
while (wrongInput) {
    if (player === playerArray[turn].name) {
        player = askPlayer();
        if (player != playerArray[turn].name) {
            wrongInput = false;
        }
    }
}
var card = askCard(player);

如您所见,第一次输入循环时,wrongInput将为true。假设玩家的姓名分别为ab而您回复baskPlayer(),则第一个if语句将为false(playerbplayerArray[0].namea)。

由于循环中没有其他代码,它会直接跳转到while (wrongInput)评估...现在你陷入了一个永无止境的循环。

所以,似乎你在player = askPlayer()之后忘记了一个结束括号。

要修复它,而不是:

if (player === playerArray[turn].name) {
    player = askPlayer();
    if (player != playerArray[turn].name) {
        wrongInput = false;
    }
}

...写道:

if (player === playerArray[turn].name) {
    player = askPlayer();
}
if (player != playerArray[turn].name) {
    wrongInput = false;
}

或者,更好的是:

if (player === playerArray[turn].name) {
    player = askPlayer();
} else {
    wrongInput = false;
}