javascript - Creating Playing Cards -
javascript - Creating Playing Cards -
having issue creating objects in javascript.
trying create deck of playing cards can display want. html stuff display them, having issue understanding doing wrong in javascript creating undefined cards me.
(function () { function card (rank, suit) { this.rank = rank; this.suit = suit; }; function deck() { this.deck = new array(); this.makedeck = makedeck; this.shuffle = shuffle; this.deal = deal; } function makedeck() { var ranks = new array("a", "2", "3", "4", "5", "6", "7", "8", "9", "10", "j", "q", "k"); var suits = new array("clubs", "diamonds", "hears", "spades"); this.deck = new array(52); var i, j; (i = 0; < suits.length; i++) { (j = 0; j < ranks.length; j++) { this.deck[i*ranks.length + j] = new card(ranks[j], suits[i]); document.write("card made \n"); } } }; function shuffle() { var i, n, j, temp; (i = 0; < n; i++) { (j = 0; j < this.deck.length; j++) { k = math.floor(math.random() * this.deck.length); temp = this.deck[j]; this.deck[j] = this.deck[k]; this.deck[k] = temp; } } document.write("cards shuffled"); }; function deal() { if (this.deck.length > 0) { homecoming this.deck.shift(); } else homecoming null; }; var deck = new deck(); deck.makedeck(); deck.shuffle(); (i = 0; < 2; i++) { (j = 0; j < 5; j++) { var card = new card(deck.deal); var c = json.stringify(card); document.write(this.deck[j]); } } } ());
this problematic line :
this.deck = new card(ranks[j], suits[i]);
this.deck
supposed array includes cards, above line, you're overriding everytime single new card.
instead of this.deck = new array(52)
, utilize this.deck = []
instead, initializing empty array this.deck.
then utilize this.deck.push(new card(ranks[j], suits[i]))
force combinations of cards deck.
the problem first alternative array.push
not efficient. read this more info. wouldn't matter 52-sized array, putting on table everyone's info.
alternatively, utilize this.deck[i] = new card(ranks[j], suits[i])
populate array. utilize this.deck = []
or this.deck = new array(52)
this. either work.
javascript object
Comments
Post a Comment