I'm doing a simple blackjack game, and I got stuck on returning from object. My goal is to get return all of the 52 cards, but what I get is only the last array.
let suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'],
values = ['Ace', 'King', 'Queen', 'Jack',
'Ten', 'Nine', 'Eight', 'Seven', 'Six',
'Five', 'Four', 'Three', 'Two'
];
let deck = [];
function createDeck(deck) {
for (let i = 0; i < values.length; i++) {
for (let j = 0; j < suits.length; j++) {
let card = {
values: values[i],
suit: suits[j]
};
deck.push(card);
}
}
return deck;
}
function cardName(deck) {
let name = [];
for (let i = 0; i < deck.length; i++) {
name = deck[i].values + " of " + deck[i].suit;
}
return name;
}
I've tried an array of object, debugging bunch of times, double looping, for...in loop, but none of it worked. My best shot is when it returns the last array, which is 'Two of Spades'. I'd really appreciate some guidance
cardName overwrites "name" in each iteration of for loop (that is why you see only the last value). Use
name.push(deck[i].values + " of " + deck[i].suit)
In function cardName in for loop each time you overwrite all the object, but not add value to array. That's why you receive only the last value. Just change name = ... to name.push(...)
To add to the above answers (that switching name =
to name.push(
will fix the problem), this could also be a great opportunity to wade into the functional areas of Javascript.
function cardName(deck) {
let name = [];
for (let i = 0; i < deck.length; i++) {
name = deck[i].values + " of " + deck[i].suit;
}
return name;
}
could be rewritten as
function cardName(deck) {
return deck.map(card => card.values + ' of ' + card.suit);
}
At least, if I'm correct in my assumption of how the deck
objects are being created here.
Feel free to reach out if this is an area you're interested in exploring!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.