简体   繁体   中英

How to fill an array using class instantiation

I am learning JavaScript. I found this question online and trying to do this.

Create 2 classes "Card" and "Deck" that will represent a standard deck of 52 playing cards. Example Ace of Spades or 5 of Hearts.

Card class that takes 2 params "suit" and "rank" and stores them as public properties. Deck class has a constant array of suits[S, C, D, H]. Deck has a constant array of ranks[2,3,4,5,6,7,8,9,10,J,Q,K,A]. Deck has an empty "cards" array

On instantiation of Deck, fill the cards array with all 52 standard playing cards using the "Card" class

I did this with just the Deck class by looping over the array. But how to do it with a separate class?

 class Deck { suits = ["S", "C", "D", "H"]; ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]; constructor(suits, ranks) { this.suits = suits; this.ranks = ranks; this.cards = []; } getAllCards() { var cards = new Array(); for (var i = 0; i < suits.length; i++) { for (var x = 0; x < cards.length; x++) { var card = { Value: cards[x], Suit: suits[i] }; cards.push(card); } } } return cards; }

You can use a Card class instead of an object to represent each card.

 class Card { constructor(suit, rank) { this.suit = suit; this.rank = rank; } } class Deck { static suits = ["S", "C", "D", "H"]; static ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]; constructor() { this.cards = this.getAllCards(); } getAllCards() { var cards = []; for (var i = 0; i < Deck.suits.length; i++) { for (var j = 0; j < Deck.ranks.length; j++) { var card = new Card(Deck.suits[i], Deck.ranks[j]); cards.push(card); } } return cards; } } console.log(new Deck().cards);

As Scott Sauyet suggests, the flatMap and map operations can also be applied for more concise code.

 class Card { constructor(suit, rank) { this.suit = suit; this.rank = rank; } } class Deck { static suits = ["S", "C", "D", "H"]; static ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]; constructor() { this.cards = Deck.suits.flatMap(suit => Deck.ranks.map(rank => new Card(suit, rank))); } } console.log(new Deck().cards);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM