2

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?

5
  • 1
    -hisses like a cat- Don't use new Array()! Use array literals: ["A","2",...]; Commented May 25, 2014 at 22:47
  • @NiettheDarkAbsol Does it really matter? Commented May 25, 2014 at 22:48
  • 2
    @Phil In this case it's the cause of the problem. Commented May 25, 2014 at 22:48
  • @Juhana Ah, too true! I didn't realise the internal pointer was positioned at the end of the array when using the length constructor Commented May 25, 2014 at 22:50
  • Bioaim - Learn to use your browser's debugging tool. This will help you identify problems like this in the future. Commented May 25, 2014 at 23:01

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"JavaScript has variable-length arrays." <-- very important distinction
Not 52 elements actually. Just a .length of 52, it's a sparse array.
thank you very much, it works now.. but i don't push more then 52 elements in the array. its length is actually 52.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.