为什么这个if语句总是正确的;不要

Why is this if statement always true when it shouldn't be?

本文关键字:不要 if 语句 为什么      更新时间:2023-09-26

我正在制作一个游戏,目标是使用普通牌组获得4对。当我提示玩家想要询问另一位玩家的卡值时,即使卡变量包含卡数组的值,else if (playerArray[turn].cards.indexOf(card) == -1)也总是求值为true。这对我来说毫无意义,我被困在如何解决这个问题上。如有任何建议,我们将不胜感激。

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
        }
    }

使用

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