简单纸牌游戏javascript中的indexOf问题
issue with indexOf in simple card game javascript
我想做一个非常简单的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()
检查数组是否为字符串-在这种情况下,您正在尝试匹配数组对象(而不是字符串)。
你可以使用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);
相关文章:
- 在指令控制器中使用$attrs时出现问题
- 将PHP变量传递给jQuery时遇到问题
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- 参数变量出现ngTable指令问题
- 剑道网格jQuery动画()问题
- 我的jQuery插件参数没有正确启动,遇到了问题
- Phonegap-(安卓/iphone)多个图像的图像库出现问题
- TableExport jquery插件:文件名和扩展名问题
- JavaScript Pub/Sub属性访问问题
- JavaScript异步问题
- 如何解决Yii中的页面刷新问题
- Safari(Mac OS)上的jQuery平滑滚动问题
- jqGrid树网格问题
- 使用正则表达式评估电子邮件地址时出现性能问题
- jQuery同位素if/else使用indexOf时出现问题
- javascript与indexOf有问题
- 简单纸牌游戏javascript中的indexOf问题
- 数组indexOf和过滤器实现的IE给其他问题
- Javascript数组indexOf by Key,Value问题
- 子字符串上的indexOf和lastIndexOf问题-从字符串中获取URL的一部分