简体   繁体   English

如何使用 class 实例化填充数组

[英]How to fill an array using class instantiation

I am learning JavaScript.我正在学习 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.创建 2 个类“Card”和“Deck”,它们将代表 52 张扑克牌的标准牌组。 Example Ace of Spades or 5 of Hearts.例如黑桃 A 或红桃 5。

Card class that takes 2 params "suit" and "rank" and stores them as public properties.卡 class 接受 2 个参数“suit”和“rank”并将它们存储为公共属性。 Deck class has a constant array of suits[S, C, D, H].甲板 class 有一组固定的花色[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 有一个常数数组[2,3,4,5,6,7,8,9,10,J,Q,K,A]。 Deck has an empty "cards" array Deck 有一个空的“cards”数组

On instantiation of Deck, fill the cards array with all 52 standard playing cards using the "Card" class在 Deck 实例化时,使用“Card”class 用所有 52 张标准扑克牌填充卡片数组

I did this with just the Deck class by looping over the array.我通过循环阵列仅使用Deck class 做到了这一点。 But how to do it with a separate class?但是如何使用单独的 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.您可以使用Card class 而不是 object 来表示每张卡片。

 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.正如Scott Sauyet所建议的, flatMapmap操作也可以应用于更简洁的代码。

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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