【问题标题】:issue with indexOf in simple card game javascript简单纸牌游戏javascript中的indexOf问题
【发布时间】:2014-06-19 03:19:57
【问题描述】:

我正在尝试制作一个非常简单的 javascript 纸牌游戏,但遇到了一个我似乎无法弄清楚的小问题。基本上下面的代码应该建立一副纸牌......这个问题在下面的代码中进行了评论,我有一些脚本应该随机地将花色和价值分配给卡片并将它们推入甲板大批。 if 语句中的 indexOf 方法应该检查是否已经将随机卡推到游戏牌组以防止重复卡,但我似乎仍然得到重复。希望有人能指出我正确的方向:

//selecting the cards types for the deck.
var cards = []; 
var numberedCards = [2, 3, 4, 5, 6, 7, 8, 9, 10];
var faceCards = ["Jack", "Queen", "King", "Ace"];
var suit = ["of hearts", "of diamonds", "of clubs", "of spades"];

while (!(cardOptions == "a" || cardOptions == "b" || cardOptions == "c")) {
    var cardOptions = prompt("What cards do you need? \nType 'a', 'b', 'c'.\na. All cards \nb. Face cards only \nc. Numbered cards only");
    switch (cardOptions) {
        case "a":
            cards = numberedCards.concat(faceCards);
            break;
        case "b":
            cards = faceCards; 
            break;
        case "c":
            cards = numberedCards;
            break;
        default:
            alert("You have to choose one an option");
    }
    console.log("You have chosen cards " + cards + ". Let's add the suits to make your deck.");
}

//the following code is supposed to:
///Randomly assign suits to the cards and push the cards into array playingDeck.  
//"indexOf" is suppose to tell me if the randomCard is already in the playingDeck, but 
//I'm still getting duplicate cards.

var playingDeck = [];

do {
    var randomNumberCard = cards[Math.floor(Math.random()*cards.length)];
    var randomSuitCard = suit[Math.floor(Math.random()*suit.length)];
    var randomCard = [[randomNumberCard],[randomSuitCard]];

    if(playingDeck.indexOf(randomCard) === -1) {
        playingDeck.push(randomCard);
        continue;
    }
    else {
        continue;
    }
} while (playingDeck.length <= cards.length*suit.length - 1);

console.log(playingDeck);
console.log("ok, you now have " + playingDeck.length + " to play with.");

在此先感谢您的帮助!

【问题讨论】:

  • 如果 indexOf 用于查找复杂对象,您应该提供您的实现。在这里查看讨论stackoverflow.com/questions?page=2&sort=newest
  • 很抱歉,但我不确定我是否理解您所说的实现的意思,这是对 javascript 类的介绍,这是迄今为止我必须展示的唯一代码。跨度>

标签: javascript if-statement indexof


【解决方案1】:

.indexOf() 检查数组中的字符串 - 在这种情况下,您尝试匹配数组对象(不是字符串)。

您可以使用 jQuery 的 $.inArray() 方法,或者像这样遍历您的卡片组:

var found = false;
for ( var card in playingDeck ) {
   if (card[0] == randomCard[0] && card[1] == randomCard[1] ) {
    found == true;
   }
}

if ( !found ) playingDeck.push(randomCard);

【讨论】:

  • .indexOf() 检查数组中的字符串不是很正确。当然你可以用它来做这个,但实际上你也可以扫描普通字符串来寻找一些包含的东西。例如var foo = "hello world"; alert(foo.indexOf("wo")); 会输出什么 6
猜你喜欢
  • 2017-12-17
  • 2011-08-02
  • 1970-01-01
  • 2013-11-02
  • 2021-07-03
  • 2010-10-12
  • 2021-03-05
  • 1970-01-01
  • 2014-06-18
相关资源
最近更新 更多