I have the following code and I want to make the deck array full of 52 different cards. Whenever I run the code and the card object is alerted it displays as '[object Object]'.
Can someone explain to me why it does this and a solution for this problem?
var suits = ["Clubs", "Diamonds", "Hearts", "Spades"];
var ranks = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];
var deck = [];
for (var i = 0; i < suits.length; i++) {
for (var j = 0; j < ranks.length; j++) {
var card = {rank: ranks[j], suit: suits[i]};
deck.push(card);
alert(card)
}
}
Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.
JavaScript lets you create objects and arrays. Objects are similar to classes. The objects are given a name, and then you define the object's properties and property values. An array is an object also, except arrays work with a specific number of values that you can iterate through.
We can use the forEach method to loop through each element in an object and add a property to each. We have the arr array. Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value. according to the console log.
Why it does this
This is perfectly normal. The card object you create doesn't know how to represent itself when you do your alert()
, simply because there are no toString()
method implementation.
Solution for your problem
Try specifying an anonymous toString()
function implementation to each card object like this:
var suits = ["Clubs", "Diamonds", "Hearts", "Spades"];
var ranks = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];
var deck = [];
for (var i = 0; i < suits.length; i++) {
for (var j = 0; j < ranks.length; j++) {
var card = {
rank: ranks[j],
suit: suits[i],
toString : function() { return this.rank + ' ' + this.suit; }
};
deck.push(card);
//alert(card); // console.log doesn't block code execution
console.log(card.toString());
}
}
Note
You should consider using console.log()
instead of alert()
as it is much less annoying and easier to debug in console (hit F12). But be careful with production code running IE9 or lower as their javascript engine will crash when the developper console is not opened.
This happens because you specify the entire object to alert, and alert does not know which properties are relevant. If you want an expandable view of your object, you can use console.log(card)
, this will output your object as a tree-view into the browser developer console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With