if statement - issue with indexOf in simple card game javascript -
if statement - issue with indexOf in simple card game javascript -
i'm trying create simple javascript card game having little issue can't seem figure out. next code supposed build deck of cards... issue commented in code below, have bit of script supposed randomly assign suits , values cards , force them deck array. indexof method in if statement supposed check if random card has been pushed playing deck prevent duplicate cards still seem getting duplicates. can point me in right direction on this:
//selecting cards types deck. var cards = []; var numberedcards = [2, 3, 4, 5, 6, 7, 8, 9, 10]; var facecards = ["jack", "queen", "king", "ace"]; var suit = ["of hearts", "of diamonds", "of clubs", "of spades"]; while (!(cardoptions == "a" || cardoptions == "b" || cardoptions == "c")) { var cardoptions = prompt("what cards need? \ntype 'a', 'b', 'c'.\na. cards \nb. face cards \nc. numbered cards only"); switch (cardoptions) { case "a": cards = numberedcards.concat(facecards); break; case "b": cards = facecards; break; case "c": cards = numberedcards; break; default: alert("you have take 1 option"); } console.log("you have chosen cards " + cards + ". let's add together suits create deck."); } //the next code supposed to: ///randomly assign suits cards , force cards array playingdeck. //"indexof" suppose tell me if randomcard in playingdeck, //i'm still getting duplicate cards. var playingdeck = []; { var randomnumbercard = cards[math.floor(math.random()*cards.length)]; var randomsuitcard = suit[math.floor(math.random()*suit.length)]; var randomcard = [[randomnumbercard],[randomsuitcard]]; if(playingdeck.indexof(randomcard) === -1) { playingdeck.push(randomcard); continue; } else { continue; } } while (playingdeck.length <= cards.length*suit.length - 1); console.log(playingdeck); console.log("ok, have " + playingdeck.length + " play with.");
thanks in advance help this!
.indexof()
checks arrays strings - in case trying match array object (not string).
you can either utilize jquery's $.inarray()
method, or iterate through card deck this:
var found = false; ( var card in playingdeck ) { if (card[0] == randomcard[0] && card[1] == randomcard[1] ) { found == true; } } if ( !found ) playingdeck.push(randomcard);
javascript if-statement indexof
Comments
Post a Comment