Javascript - 如何在函数中使用变量

时间:2016-11-12 16:21:36

标签: javascript string function variables

我是一个新手试图建立一个德州扑克扑克游戏进行练习。为了简单起见,假设我有4个玩家,我们在第4轮比赛中,所以我的经销商筹码将在玩家4。同样为了简单起见,我们开始处理经销商筹码,即玩家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();
}

这是我的问题 - 当我尝试直接在player4上使用交易功能时(deal(player4);),它运行正常。

但是当我在dealerChip(deal(dealerChip);)上使用交易功能时,它等于player4,它不起作用。

是因为dealerChip变量实际上是一个字符串吗?我该怎么改变?对不起,如果问题重复 - 我太新手甚至不知道要搜索什么......

1 个答案:

答案 0 :(得分:0)

以下是我认为你想要做的一个例子。您需要使用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