Javascript-如何删除数组中数组的所有元素

时间:2018-10-10 09:25:47

标签: javascript

当前,当我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变量中,但是它给我索引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);
}

1 个答案:

答案 0 :(得分:2)

您可以对结果集使用单个组合对象。还有一个对象,可以更短地获得积分。

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

相关问题