Provide an object property with an array value?

I have the following code, and I want to make an array of decks consisting of 52 different cards. Whenever I run the code and the map object is warned, it is displayed as "Object Object".

Can someone explain to me why he is doing this and the solution to 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) } } 
+6
source share
5 answers

Why does it do

This is completely normal. The created map object does not know how to present itself when you execute your alert() , simply because there is no implementation of the toString() method.

Solution

Try specifying an anonymous implementation of the toString() function for each map object as follows:

 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 use console.log() instead of alert() , since it is much less annoying and easier to debug the console (press F12). But be careful with production code running under IE9 or lower, as their javascript engine will work when the development console is not open.

+6
source

This is because you are pointing the entire object to a warning, and the warning does not know which properties are relevant. If you want to expand access to your object, you can use console.log(card) , this will lead to the output of your object in the form of a tree to the browser developer console.

+2
source

So the object is shown, its toString method only displays this to see its contents using

 alert(JSON.stringify(card)); 
0
source

FIDDLE DEMO

Replace your warning with this -> alert (JSON.stringify (card))

 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(JSON.stringify(card))//CHANGE THIS... console.log(JSON.stringify(card)) } } 

EXPLANATION

JSON.stringify converts JavaScript data structures to JSON text. Json text is nothing more than a key: a pair of text.It can not simple values.

0
source

You should change your warning:

 alert(JSON.stringify(card)) 
0
source

Source: https://habr.com/ru/post/949589/


All Articles