首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript -如何删除数组中的所有元素

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

Stack Overflow用户
提问于 2018-10-10 17:25:47
回答 1查看 99关注 0票数 1

目前,当I console.log(deckOfCards)时,它返回所有52张牌,每张牌都有花色、值和分配给它们的点数。

代码语言:javascript
复制
{ suit: '♦', value: 'A', points: 11 }
{ suit: '♦', value: 2, points: 2 }
{ suit: '♦', value: 3, points: 3 }
.....

现在,我想从我的deckOfCards数组中删除包含花色、值和点数的一张牌,并将其返回。

代码语言:javascript
复制
{ suit: '♦', value: 'A', points: 11 }

这是模拟处理一副牌中的一张牌。

我尝试访问数组的每个索引并将它们添加到card变量中,但它给了我一个未定义的for index 2。

For循环只返回一个套装数组,而不返回其他数组。

我已将deckOfCards更改为其中包含套装、值和点的对象。

我的卡片常量是我想要从一副牌中拉出一张卡片的地方。

代码语言:javascript
复制
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

 }
}

正在尝试添加新方法的编辑

我尝试将两张牌分别添加到玩家/发牌者手中,但当我记录时:

代码语言:javascript
复制
[ { suit: '♠', value: 'A', points: 11 } ]
[ { suit: '♠', value: 'A', points: 11 },
  { suit: '♦', value: 10, points: 10 } ]

为什么返回的是3个对象而不是2个?

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-10 17:42:28

您可以对结果集使用单个组合对象。和一个对象,用于更短的获取点数的方式。

代码语言:javascript
复制
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);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52736888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档