0

在我生成扑克牌的脚本中,它生成了一个 0,即使我的随机生成器添加了一个 1,所以它永远不应该是 0。我做错了什么?!如果你刷新,你最终会得到一个“红桃/俱乐部/钻石/黑桃0”:

var theSuit;
var theFace;
var theValue;
var theCard;

// deal a card
function generateCard() {
    var randomCard = Math.floor(Math.random()*52+1)+1;  
    return randomCard;
};

function calculateSuit(card) {
    if (card <= 13) {
        theSuit = "Hearts";
    } else if ((card > 13) && (card <= 26)) {
        theSuit = "Clubs";      
    } else if ((card > 26) && (card <= 39)) {
        theSuit = "Diamonds";
    } else {
        theSuit = "Spades";
    };  

    return theSuit;
};

function calculateFaceAndValue(card) {
    if (card%13 === 1) {
        theFace = "Ace";
        theValue = 11;
    } else if (card%13 === 13) {
        theFace = "King";
        theValue = 10;          
    } else if (card%13 === 12) {
        theFace = "Queen";
        theValue = 10;
    } else if (card%13 === 11) {
        theFace = "Jack";
        theValue = 10;
    } else {
        theFace = card%13;
        theValue = card%13;
    };

    return theFace;     
    return theValue
};

function getCard() {
    var randomCard = generateCard();        
    var theCard = calculateFaceAndValue(randomCard);
    var theSuit = calculateSuit(randomCard);            
    return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};

// begin play
var myCard = getCard();
document.write(myCard);`
4

2 回答 2

4

This line is problematic:

} else if (card%13 === 13) {

Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )

Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.

于 2012-06-16T15:58:59.130 回答
3
card%13 === 13

This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:

card % 13 === 0

return theFace;     
return theValue

return exits the function; you'll never get to the second statement.

于 2012-06-16T16:00:03.457 回答