[英]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 // 制作一副 52 张牌
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
.由于创建的deck 实例附加到deck 变量,您可以通过执行
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你也可以使用 Math.round 函数,这取决于你想要的精确度
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)];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.