I just started learning javascipt and am stumped at this error in the middle of a tutorial:
I'm trying to create a mini-game of sorts where I flip cards and find matches.
I have objects in an array and am trying to call the particular value of 'rank' depending on which card(object) is chosen.
Running the code in console gives me an error: Uncaught TypeError: Cannot read property 'rank' of undefined.
Javascript:
console.log("Up and running");
var cards = [
{
rank: "queen",
suit: "hearts",
cardImage: "images/queen-of-hearts.png"
},
{
rank: "queen",
suit: "diamonds",
cardImage: "images/queen-of-diamonds.png"
},
{
rank: "king",
suit: "hearts",
cardImage: "images/king-of-hearts.png"
},
{
rank: "king",
suit: "diamonds",
cardImage: "images/king-of-diamonds.png"
}
];
var cardsInPlay = [];
var checkForMatch = function() {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
} else alert("Sorry, try again");
}
var flipCard = function(cardId) {
console.log("User flipped " + cards[cardId].rank);
/*issue is with calling the rank*/
console.log(cards[cardId].cardImage);
console.log(cards[cardId].suit);
cardsInPlay.push(cards[cardId].rank);
if (cardsInPlay.length === 2) {
checkForMatch();
};
}
var createBoard = function() {
for (var i = 0; i < cards.length; i ++) {
var cardElement = document.createElement('img');
cardElement.setAttribute("img", "images/back.png");
cardElement.setAttribute("data-id", i);
cardElement.addEventListener("click", flipCard());
document.getElementById("game-board").appendChild(cardElement);
}
}
createBoard();
flipCard(0);
flipCard(2);
Is my error due to the way I call the value from the object using cards[cardId].rank?