I'm new to JS (first week) doing a command line card game for a school project. I've been able to get through the first three exercises (2 & 3 have been omitted).
However, I don't understand why I'm unable to access the property value
from deck
I've looked around for a solution including here:
StackOverflow: compare two numeric String values
Medium (Nothing on comparing cards. PT2 includes HTML which we're not doing.): https://medium.com/@pakastin/javascript-playing-cards-part-1-ranks-and-values-a9c2368aedbd
Stack Overflow (this question was downvoted): How to compare 2 cards in a JavaScript card game
I am able to build the deck (Exercise 1):
function buildDeck() {
const suits = ['spades', 'hearts', 'diamonds', 'clubs'];
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const deck = [];
for (let r = 0; r < ranks.length; r++) {
for (let s = 0; s < suits.length; s++) {
deck.push({ ranks: ranks[r], suits: suits[s], value: r + 1 });
}
}
return deck;
}
console.log(buildDeck())
This returns the ranks
, suits
, and value
for each card.
Next, I try to solve the problem of comparing the cards (Exercise 4):
const compare = (firstCard, secondCard) => {
const cardValue = firstCard.value - secondCard.value;
return cardValue;
}
console.log(compare());
However, when I try to return the value property of the first card minus the second card, I get the following error:
const cardValue = firstCard.value - secondCard.value;
TypeError: Cannot read property 'value' of undefined
If I remove .value
from the code, I, of course, get NaN
because there is not an object from the array to compare it with.
I'm stuck at this point and not sure how to get the difference between the cards. Any advice/help is greatly appreciated.