为什么这个if语句总是不正确的呢?

时间:2014-10-20 18:09:55

标签: javascript

我正在制作一款游戏,其目标是使用正常的牌组获得4对。当我提示玩家想要向另一个玩家询问哪个卡值时,即使卡变量包含卡片阵列的值,else if (playerArray[turn].cards.indexOf(card) == -1)总是评估为真。这对我来说毫无意义,我仍然坚持如何解决这个问题。非常感谢任何建议。

var playerArray = [];       //Holds the player objects
var turn = 0;               //Keeps track of whose turn it is
var wrongCard = true;
var card = askCard(player); //Prompt to get a card value

function askCard(player) {

    var whichCard = prompt('The deck has: ' + deck.length + ' cards left in it.\n'
    + 'Your current cards are: ' + playerArray[turn].cards.join(' - ') + '\n'
    + player + ', all your:');

    return whichCard;
}

    while (wrongCard) { //Run as long as the card input is wrong

        if (card < 1 || card > 13) { //If card value is not between 1-13
            card = askCard(player);
        }

        //If the asked card doesn't exist in the current player's cards array
        else if (playerArray[turn].cards.indexOf(card) == -1) { //ALWAYS TRUE, WHY?
            card = prompt('The deck has: ' + deck.length + ' cards left in it.\n' +
                          'Your current cards are: ' + playerArray[turn].cards.join(' - ') 
                          + '\n' + player + ', all your:');
        }

        else {
            wrongCard = false; //Jump out of loop
        }
    }

1 个答案:

答案 0 :(得分:3)

使用

playerArray[turn].cards.indexOf(parseInt(card,10)) == -1)