madna madna - 4 months ago 32
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) {

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...


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) {

obj.dealerChip = "player4";

//now, to call deal()

//what you do and works because player4 is an array
//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".
//Therefore, it can be rewritten as:
//which can also be rewritten as:
//which is the same as the original you attempted