0

This is my code:

var shuffle = function(x) {
    var deck = [];
    deck.push(x);

    return deck;
};

var Placemat = function() {
    var card1 = deck.shift();
    var card2 = deck.shift();
}

By returning deck in shuffle() like this, can I use it in Placemat()? If not, how can I do it?

2
  • 1
    I don't know about that username bro. Commented Aug 10, 2011 at 20:28
  • @Triptych--fair enough, but do you know the answer? Commented Aug 10, 2011 at 20:30

4 Answers 4

2

Yes you could. But anytime you call .shuffle() you would overwrite that array, or more precisely, create a new instance. So if you want to keep that reference you could go like

var shuffle = (function() {
    var deck = [];

    return function(x) {
        deck.push(x);

        return deck;
    };
}());

Now .shuffle() closes over the deck by returning another function. So it could look like

var Placemat = function() {
    var myDeck = shuffle(5);

    shuffle(10);
    shuffle(15);

    var card1 = deck.shift();
    var card2 = deck.shift();
}

Even if that is probably not the greatest way to go. But I guess I don't even know what exactly you want to achieve there.

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

1 Comment

Shouldn't it be myDeck.shift() ?
0

You cannot you have to put them in the parameters or outside the function.

var shuffle = function(x) {
    var deck = [];
    deck.push(x);

    return deck;
};

 var Placemat = function(deck) {
    var card1 = deck.shift();
    var card2 = deck.shift();
}

or 

var deck = [];
var Placemat = function() {
    var card1 = deck.shift();
    car card2 = deck.shift();
}

Comments

0

You can use the return value from shuffle in Placemat, but it will always be an array with a single item in it.

If you want to have a variable deck that contains multiple items, deck will need to be declared in an outer scope:

var deck = [];

var shuffle = function(x) {
    deck.push(x);
    return deck;
}

var Placemat = function() {
    var card1 = deck.shift();
    var card2 = deck.shift();
};

This way, both the shuffle function and Placemat are using the same variable deck.

Comments

-1

I found another solution:

var shuffle = function(deck,x) {
    var deck = [];
    deck.push(x);

    return deck;
};

var Placemat = function() {
    var newdeck = shuffle(deck,x)
    var card1 = newdeck.shift();
    var card2 = newdeck.shift();
}

This way I don't have to make deck a global variable. Thanks for the help everyone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.