21点Javascript:尝试将所有卡添加到牌组中(我这样做正确吗?)
因此,我正在通过Javascript创建一个21点游戏,我试图做的是设置所有的牌,并将其添加到牌组中。当我尝试这一点,并在控制台检查,它没有工作,我似乎无法找到我做错了什么。我走对了吗?我会把我的东西贴出来。我才刚刚开始。任何帮助都将不胜感激。谢谢21点Javascript:尝试将所有卡添加到牌组中(我这样做正确吗?),javascript,Javascript,因此,我正在通过Javascript创建一个21点游戏,我试图做的是设置所有的牌,并将其添加到牌组中。当我尝试这一点,并在控制台检查,它没有工作,我似乎无法找到我做错了什么。我走对了吗?我会把我的东西贴出来。我才刚刚开始。任何帮助都将不胜感激。谢谢 var card = function(value, name, suit) { this.value = value; this.name = name; this.suit = suit; } var deck = function
var card = function(value, name, suit) {
this.value = value;
this.name = name;
this.suit = suit;
}
var deck = function() {
this.names = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
this.suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs'];
this.values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11];
var cards = [];
for (var s = 0; s < this.suits.length; s++) {
for (var n = 0; n < this.name.length; n++) {
cards.push((this.values[n], this.names[n], this.suits[s]));
}
}
return cards;
}
var卡=功能(值、名称、套装){
这个值=值;
this.name=名称;
这套衣服;
}
var deck=函数(){
this.names=['2','3','4','5','6','7','8','9','10','J','Q','K','A'];
this.suits=[‘红心’、‘钻石’、‘黑桃’、‘梅花’];
这个值=[2,3,4,5,6,7,8,9,10,10,10,11];
var卡=[];
对于(var s=0;s
鉴于您是javascript新手,我建议更改设计模式:
function Card(value, name, suit){
this.value = value;
this.name = name;
this.suit = suit;
}
// Allows to print nice card name
Card.prototype.toString = function() {
if(this.value==11 && this.suit == "Spades")
return "Ace of spades";
else
return this.suit+" "+this.name;
}
function Deck() {
this.cards = [];
}
Deck.prototype.createAllCards = function() {
for (var s = 0; s < Deck.suits.length; s++) {
for (var n = 0; n < Deck.names.length; n++) {
this.cards.push(new Card(Deck.values[n], Deck.names[n], Deck.suits[s]));
}
}
}
// These are so called static properties on OOP
// We can just assign those values to Deck() function
// Because they never ever change
Deck.names = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
Deck.values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11];
Deck.suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs'];
// Initialise
var deck = new Deck();
deck.createAllCards();
console.log(deck.cards);
只有#1起作用。为什么要用
var
声明所有函数?使用该语法,函数在定义之前不可用。for(var n=0;n
names上的s
你漏掉了。@T.J.Crowder你是对的,不过还有一个错误,那就是names
和values
的长度不同。但我认为他应该有机会得到一些关于这段代码的提示,尽管我知道这不是一般的目的。但与许多其他的初学者,他至少试着写代码。…。@T.J.Crowder-我指的是如何调用card函数。嗯,它根本没有被调用,但OP试图调用它(在cards.push()
),他们没有使用新的关键字。@dustmouse:没错,push
行每次都会将'Hearts'
,'Diamonds'
,'Spades'
,或'Clubs'
推到卡数组上。一定喜欢那个逗号操作符。:-)
smile()
function smile() {console.log(":)")};
smile()
var smile = function() {console.log(":)")};