我该如何修改这段代码来使每张卡片都变成一个对象呢?
How would I fix this code to make each card into an object?
我有这个程序,创建不同的牌(从9到a)在每个花色(红心,方块,梅花,黑桃),但我希望每张牌成为一个对象,以便我可以访问每张牌花色和值。
//This part of the code creates the card, this is what I will need to change.
function card (name , suit) {
window.cardsuit = suit;
window.cardname = name;
}
//This is the deck object it contains the code for making the deck
var deck = {
//The list of suits
suit: suits = ["Diamond", "Heart", "Club", "Spade"],
//The list of card names
name: names = ["Nine", "Ten", "Jack", "Queen", "King", "Ace"],
//Array of cards
cards: cards = [],
//This function repeats to create each card
createcards: function(){
for (var i = 0; i < suits.length; i++){
for (var j = 0; j < names.length; j++){
card(names[j], suits[i]);
deck.cards.push(window.cardname + window.cardsuit);
}
}
},
//This function is used later on to draw a card randomly from the deck
draw: function (player){
var randnumber = Math.floor((Math.random() * deck.cards.length));
player.push(deck.cards[randnumber]);
deck.cards.splice(randnumber, 1);
}
};
//Object of the player hands
var hand = {
//This deals out the players hands
dealhands: function dealhands(amount) {
t = 0;
var player_one = [];
var player_two = [];
var player_three = [];
var player_four = [];
var kitty = [];
//Deals it however many times I would like the cards dealt
while (t < amount){
deck.draw(player_one);
deck.draw(player_two);
deck.draw(player_three);
deck.draw(player_four);
deck.draw(kitty);
alert(player_one[0]);
t ++;
}
}
};
我相信我需要使用"this"关键字,但我不知道如何在这种情况下使用它。谢谢。
定义一个"类" (javascript没有类,它是原型,但"类"是一个有用的词来描述它):
function Card (rank , suit) {
this.suit = suit;
this.rank = rank;
}
var ace_of_spades = new Card('A','♠');
deck.cards.push(ace_of_spades);
否则你在这里看起来不错。在卡片中,术语"名称"在技术上被称为"等级",所以我更改了这些变量的名称。
你在这里创建了全局变量,这是不好的:
suit: suits = ["Diamond", "Heart", "Club", "Spade"],
//The list of card names
name: names = ["Nine", "Ten", "Jack", "Queen", "King", "Ace"],
//Array of cards
cards: cards = [],
保留为:
suit: ["Diamond", "Heart", "Club", "Spade"],
//The list of card names
ranks: ["Nine", "Ten", "Jack", "Queen", "King", "Ace"],
//Array of cards
cards: [],
相关文章:
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- AngularJS&JSON-从Previous&下一个对象
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript函数,它接受两个输入:一个对象和一个键,并返回对象中该键的相应值
- 你能用来自数组的属性名称生成一个对象吗
- 预期响应包含一个对象,但在angular js中得到一个数组错误
- Protractor:element.getText()返回一个对象,而不是String
- 如何使用jQuery添加另一个对象的高度作为边距
- 计算从一个对象到另一个对象的路径并沿其移动
- 如何将一个对象添加到每个对象数组中
- 为了避免创建全局变量,可以将所有变量分配给一个对象吗
- 将javascript对象(属性+值)合并到一个对象中
- 尝试简化检查对象键是否为true并将其推送到另一个对象
- 从 javascript 中的对象方法返回一个对象
- 响应应包含一个对象,但得到的却是GET操作的数组
- js:如何制作一个循环,将20个不同的东西添加到一个对象中
- 我该如何修改这段代码来使每张卡片都变成一个对象呢?