[英]How to differentiate between variables passed into function?
我正在开发一个自动二十一点游戏(一直运行到没有用户输入就完成)。
let randomDeal = () => {
let cardOne = Math.ceil(Math.random() * 10);
let cardTwo = Math.ceil(Math.random() * 10);
return cardOne + cardTwo;
}
let player = randomDeal();
let dealer = randomDeal();
console.log("Your hand: " + player);
console.log("Dealer's hand: " + dealer);
let hit = (hand) => {
if (hand <= 16){
hand += Math.ceil(Math.random() * 10);
console.log("Second hand: " + hand);
if (hand <= 21){
hand += Math.ceil(Math.random() * 10);
console.log("Third hand: " + hand);
}
}else{
console.log("Stay: " + hand);
}
}
hit(player);
hit(dealer);
到目前为止,它是这样的:
$ babel-node main.js
Your hand: 6
Dealer's hand: 4
Second hand: 11
Third hand: 19
Second hand: 10
Third hand: 15
我对如何将player
和dealer
牌人都传递到hit函数中并使它们作为player
和发dealer
人返回其值感到困惑。 现在很难将它们分开。
理想输出:
$ babel-node main.js
Your hand: 6
Dealer's hand: 4
Your second hand: 11
Your third hand: 19
Dealer's second hand: 10
Dealer's third hand: 15
使用对象? 开始:
let ob = {
player: 0,
dealer: 0
}
发布功能:
ob = {
player: 18,
dealer: 19
}
不可以,函数无法区分用于计算其参数的变量(或任何其他表达式)。 它只能区分值。
对于您的情况,您应该考虑使用第二个参数和播放器名称(的真实名称):
function hit (hand, prefix) {
if (hand <= 16) {
hand += Math.ceil(Math.random() * 10);
console.log(prefix+" second hand: " + hand);
if (hand <= 21) {
hand += Math.ceil(Math.random() * 10);
console.log(prefix+" third hand: " + hand);
}
} else {
console.log(prefix+" stay: " + hand);
}
}
hit(player, "Your");
hit(dealer, "Dealer's");
为了简单起见,您可以只返回两个项目的数组吗?
return [player, dealer];
然后在调用函数中:
result = hit(player, dealer);
player = result[0];
dealer = result[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.