0
function CreateSuit(suit){
  this.suit = suit;
  this.vaule = i;
  this.name = name;
}

var twoClubs = new Card ('clubs', 2, 'two of clubs');
var threeClubs = new Card ('clubs', 3, 'three of clubs');
var fourClubs = new Card ('clubs', 4, 'four of clubs');

var deck = [];

How do I put these objects into the deck array? Sorry if this is a dumb question I am having trouble finding an answer.

2
  • 2
    deck.push(twoClubs) Commented Jan 18, 2016 at 5:37
  • 1
    var deck = [twoClubs, threeClubs, fourClubs]; Commented Jan 18, 2016 at 5:38

3 Answers 3

1

You have a few options, as mentioned in the comments.

1) Instantiate the array with the objects:

var deck = [twoClubs, threeClubs, fourClubs];

2) Add the objects onto the array:

var deck = [];
deck.push(twoClubs);
deck.push(threeClubs);
deck.push(fourClubs);

3) You could even instantiate the array and declare the objects at the same time:

var deck = [new Card ('clubs', 2, 'two of clubs'), new Card ('clubs', 3, 'three of clubs'), new Card ('clubs', 4, 'four of clubs')];

Technically, this is the most efficient way (caveat: this is browser/implementation dependent).

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

4 Comments

“Technically, this is the most efficient way.” According to what metric?
No citation is needed. By not declaring variables outside of the array, OP will perform less operations and use (a minuscule amount of) less memory.
Or they could be rewritten to exactly the same thing by whichever engine is running them. (I think that seems likely.)
I'll argue for the less bytes send in the network request then :P
1

There are a few ways to do this. You can initialize the array with the values present:

var deck = [twoClubs, threeClubs, fourClubs]

Or you can add them to the array on the fly:

var deck = [];
deck.push(twoClubs);
deck.push(threeClubs);
deck.push(fourClubs);

Or you can even specify where in the array you want to put them:

var deck = [];
deck[2] = threeClubs;
deck[0] = fourClubs;
deck[1] = twoClubs

Or you can mix and match any of these:

var deck = [threeClubs];
deck[1] = twoClubs;
deck.push(fourClubs);

1 Comment

Awesome thank you all for the help! This give me some good options to play with!
0

Now once you have added object in array using either of methods mentioned in other answers.

var deck = [twoClubs, threeClubs, fourClubs];

or

var deck = [];
deck.push(twoClubs);
deck.push(threeClubs);
deck.push(fourClubs);

you can retrieve and remove last object from array by using

deck.pop(); // remove and return last object

or you can use indexes to retrieve object from specific location

deck[1] // returns threeClubs

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.