简体   繁体   中英

How could I shuffle and then display a random card from this array?

class Card {
   constructor(suit, value) {  
    this.suit = suit;  
    this.value = value;
    }
}

TEST IF IT LETS ME MAKE A CARD

let card = new Card('Spades', 8);
console.log(card);

// MAKE A DECK OF 52 CARDS

class Deck {
    constructor () {
        this.deck =  [];  
    }
    createDeck (suits, values) {
        for(let suit of suits) {
            for(let value of values){
                this.deck.push(new Card (suit, value));
            }
        }
        return this.deck;


    }
}
const suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
const values = [2,3,4,5,6,7,8,9,10, 'Jack', 'Queen', 'King', 'Ace']
let deck = new Deck();
deck.createDeck(suits, values);
// console.log(deck);

I can create the deck I just dont know how to pick random items fom it. Any help would be appreciated.

since the created deck instance is attached to the deck variable you can access it by doing deck.deck .

so you can do something like:

deck.deck[Math.floor(Math.random() * 52)]

you can also use the Math.round function instead, depends on how precise you want to be

you could also create a function where you then pass your deck and get a card back. for example:

function pickCard(deck) {
  return deck[Math.round(Math.random() * 52))];
}

you can implement this as a method as well

    class Deck{
     // ...your code
     get pickCard() {
      return this.deck[Math.round(Math.random() * 52)];
     }
    }

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