目前,当I console.log(deckOfCards)时,它返回所有52张牌,每张牌都有花色、值和分配给它们的点数。
{ suit: '♦', value: 'A', points: 11 }
{ suit: '♦', value: 2, points: 2 }
{ suit: '♦', value: 3, points: 3 }
.....
现在,我想从我的deckOfCards数组中删除包含花色、值和点数的一张牌,并将其返回。
{ suit: '♦', value: 'A', points: 11 }
这是模拟处理一副牌中的一张牌。
我尝试访问数组的每个索引并将它们添加到card变量中,但它给了我一个未定义的for index 2。
For循环只返回一个套装数组,而不返回其他数组。
我已将deckOfCards更改为其中包含套装、值和点的对象。
我的卡片常量是我想要从一副牌中拉出一张卡片的地方。
const suits = ["♦", "♣", "♥", "♠"];
const values = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];
for (const suit of suits) {
for (const value of values) {
let points = parseInt(value);
if(value === "J" || value === "Q" || value === "K") points = 10;
if(value === "A") points = 11;
const deckOfCards = {suit, value, points};
const card = deckOfCards
}
}
正在尝试添加新方法的编辑
我尝试将两张牌分别添加到玩家/发牌者手中,但当我记录时:
[ { suit: '♠', value: 'A', points: 11 } ]
[ { suit: '♠', value: 'A', points: 11 },
{ suit: '♦', value: 10, points: 10 } ]
为什么返回的是3个对象而不是2个?
const dealRandomCard = () => {
return deckOfCards.splice(Math.floor(Math.random() *
deckOfCards.length), 1)[0];
}
// console.log(dealRandomCard());
//////////////////////////////////////////////////////////////
for (let i = 0; i <= 1; i++) {
playerHand.push(dealRandomCard());
dealerHand.push(dealRandomCard());
console.log(playerHand);
// console.log(dealerHand);
}
发布于 2018-10-10 17:42:28
您可以对结果集使用单个组合对象。和一个对象,用于更短的获取点数的方式。
var suits = ["♦", "♣", "♥", "♠"],
values = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"],
cards = [],
suit,
value,
points = { A: 11, J: 10, Q: 10, K: 10 };
for (suit of suits) {
for (value of values) {
cards.push({ suit, value, points: points[value] || value });
}
}
function getCard() {
return cards.splice(Math.floor(Math.random() * cards.length), 1)[0];
}
console.log(getCard());
console.log(getCard());
console.log(getCard());
console.log(cards);
https://stackoverflow.com/questions/52736888
复制相似问题