madna madna - 24 days ago 7
Javascript Question

Javascript - how do I use a variable within a function

I'm a newbie trying to build a Texas Hold'em poker game for practice. For simplicity's sake, let's say I have 4 players and we are in round/game number 4, so my dealerChip will be at player4. Also for simplicity's sake, we start dealing at the dealerChip i.e. player 4.

var numberPlayers = 4;
var gameNumber = 4
var deck = ["1","3","4","2"]
var player4 = [];
var dealerChip = "player0";

if (gameNumber <= numberPlayers) {
dealerChip = "player" + gameNumber;
}
else {
var val = Math.floor((gameNumber-1) / numberPlayers);
dealerChip = "player" + gameNumber - numberPlayers * val;
};

function deal(toWhere) {
toWhere.push(deck[deck.length-1]);
deck.pop();
}


Here's my issue - when I try to use the deal function on player4 directly (deal(player4);), it works fine.

But when I use the deal function on dealerChip (deal(dealerChip);), which is equal to player4, it doesn't work.

Is it because the dealerChip variable is actually a string? How to I change this? Sorry if the question is repeated - I'm too newbie to even know what to search for...

Answer

Here is an example of what I think you're trying to do. You need to make use of javascript's bracket notation.

//place properties into object.
var obj = {
    numberPlayers: 4,
    gameNumber: 4,
    deck: ["1","3","4","2"],
    player4: [],
    dealerChip: "player0"
};

function deal(toWhere) {
    toWhere.push(obj.deck[obj.deck.length-1]);
    obj.deck.pop();
}

obj.dealerChip = "player4";

//now, to call deal()

//what you do and works because player4 is an array
deal(obj.player4); 
//what you want to do; this access the property in the obj 
//that has a name equal to the value of dealerChip. 
//In this case, dealerChip has the value of "player4".
deal(obj[obj.dealerChip]); 
//Therefore, it can be rewritten as:
deal(obj["player4"]); 
//which can also be rewritten as:
deal(obj.player4);
//which is the same as the original you attempted