[英]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.
为了简单起见,假设我有4个玩家,我们在第4轮比赛中,所以我的经销商筹码将在玩家4。 Also for simplicity's sake, we start dealing at the dealerChip ie player 4.
同样为了简单起见,我们开始在dealerChip处理,即玩家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. 这是我的问题 - 当我尝试直接在player4上使用交易功能(交易(player4);)时,它运行正常。
But when I use the deal function on dealerChip (deal(dealerChip);), which is equal to player4, it doesn't work. 但是当我在dealerChip(deal(dealerChip);)上使用交易功能时,它等于player4,它不起作用。
Is it because the dealerChip variable is actually a string? 是因为dealerChip变量实际上是一个字符串吗? 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 .
您需要使用javascript的括号表示法 。
//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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.