I am totally new to javascript, but I can program in Java, C# etc. already.
I want to generate a card deck, and after that I want to access this array of cards.
function Card(rank, suit)
{
this.rank = rank;
this.suit = suit;
}
function Deck()
{
this.ranks = new Array("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K");
this.suits = new Array("Hearts", "Clubs", "Diamonds", "Spades");
this.cards = Array(52);
this.makeDeck = function()
{
console.log("Executed MakeDeck!");
for(var i = 0; i < this.suits.length; i++)
{
for(var j = 0; j < this.ranks.length; j++)
{
this.cards.push(new Card(this.ranks[j],this.suits[i]));
}
}
}
}
function btnClick()
{
var deck = new Deck();
deck.makeDeck();
console.log(deck.cards[0]);
}
In the function "btnClick()" I want to log the first item in the array, but the console just tells my "undefined". I can't find my mistake, maybe you can help me?
Lee Taylor
7,99416 gold badges38 silver badges53 bronze badges
asked May 25, 2014 at 22:45
Bioaim
1,0161 gold badge15 silver badges28 bronze badges
1 Answer 1
The problem is that you have initialised an array with 52 elements... and you are then pushing more elements onto it.
What you need to do is just have this.cards = [];. JavaScript has variable-length arrays.
answered May 25, 2014 at 22:48
Niet the Dark Absol
326k86 gold badges480 silver badges604 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Josh Beam
"JavaScript has variable-length arrays." <-- very important distinction
Bergi
Not 52 elements actually. Just a
.length of 52, it's a sparse array.Bioaim
thank you very much, it works now.. but i don't push more then 52 elements in the array. its length is actually 52.
default
new Array()! Use array literals:["A","2",...];