I am new to programming and javascript and i have a question ive been struggling with for a bit now. Im trying to build a card game and have a card object which returns a card representation of the format (card #,suit eg. 5,Hearts). I deal a card at the start of the program and validate that the card dealt is unique (ie not been used already). I have the following structure:
var usedCards= [];
function dealCards() {
for (i = 0; i < 3; i++)
{
var card = createUniqueCard();
usedCards.push(card.cardRepresentation);
}
}
function createUniqueCard() {
do {
var newCard = new Card();
}
while (usedCards.indexOf(newCard.cardRepresentation) != -1);
return newCard;
}
This still returns me duplicate cards in my usedCards array. Can anyone point out my logic error?
Thanks
If
newCard.cardRepresentationis an object then.indexOf()will never find a match because two object references are considered equal only if they refer to the same instance – you keep creating new instances withnew Card().If you can have
newCard.cardRepresentationas a string it should work. Or if you write your own function to replace.indexOf(), where your function knows how to compare two.cardRepresentationobjects…I think a better solution is to begin by generating all possible cards, putting them in an array, and then your deal function could randomly select from that array.