Reputation: 176
Morning Guys
im currently playing with javascript and am creating a simple black jack game, i want to keep track of cards which have already been pulled from the pack. heres my function
function usedCards(value,suit)
{
var exists = false;
for(i = 0; i< usedCardNo.length;i++)
{
if (value === usedCardNo[i] && suit === usedCardSuit[i])
{
exists = true;
console.log(i);
}
}
console.log("exists = " + exists);
if (exists===false)
{
usedCardNo.push(value);
usedCardSuit.push(suit);
console.log(value + " and " + suit +" added to array");
}
}
i pass the function 2 id numbers one realting to card number ie ace, 7, 9 aswell as suit.
i then check if it already exists in the array, if not add it. but its not currently working?? it just doesnt recognise a duplicate value.
Upvotes: 0
Views: 100
Reputation: 7853
Mhm however your code seems to work for me. Have a look at this jsfiddle. It seems to show the expected output:
exists = false
1 and 2 added to array
exists = false
3 and 7 added to array
0
exists = true
What you maybe experiencing is that the function does not return anything right now. So you have to add return exists;
at the end of your function.
Upvotes: 1
Reputation: 13557
Using an array to continuously check if something is in there is a bad idea. What you actually want to be using is a map. Something along the lines of:
var used_cards = {};
function useCard(value, suit) {
var key = suit + '|' + value;
if (used_cards[key]) {
return false;
}
used_cards[key] = true;
return true;
}
Upvotes: 0
Reputation: 7569
You should fix several things:
function usedCards(value,suit){
var exists = false;
for(i = 0; i< usedCardNo.length;i++){
if (value == usedCardNo[i] && suit == usedCardSuit[i]){
exists = true;
console.log(i);
}
}
console.log("exists = " + exists);
if (exists==false){
usedCardNo.push(value);
usedCardSuit.push(suit);
console.log(value + " and " + suit +" added to array");
}
}
Upvotes: 0