简体   繁体   English

如何区分传递给函数的变量?

[英]How to differentiate between variables passed into function?

I'm working on an automatic (runs until done without user input) blackjack game. 我正在开发一个自动二十一点游戏(一直运行到没有用户输入就完成)。

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

So far it goes like this: 到目前为止,它是这样的:

$ babel-node main.js
Your hand: 6
Dealer's hand: 4
Second hand: 11
Third hand: 19
Second hand: 10
Third hand: 15

I'm confused about how to pass both player and dealer into the hit function and have them return their values back as player and dealer . 我对如何将playerdealer牌人都传递到hit函数中并使它们作为player和发dealer人返回其值感到困惑。 Right now it is hard to separate them. 现在很难将它们分开。

IDEAL OUTPUT: 理想输出:

$ 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

Using an object? 使用对象? Start: 开始:

let ob = {
  player: 0,
  dealer: 0
}

post function: 发布功能:

ob = {
  player: 18,
  dealer: 19
}

No, a function cannot differentiate between variables (or any other expressions) that were used to compute its arguments. 不可以,函数无法区分用于计算其参数的变量(或任何其他表达式)。 It can only differentiate between values. 它只能区分值。

For your case, you should consider using a second parameter with the (genitive of the) name of the player: 对于您的情况,您应该考虑使用第二个参数和播放器名称(的真实名称):

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");

For simplicity could you just return an array of the two items? 为了简单起见,您可以只返回两个项目的数组吗?

return [player, dealer];

Then in the calling function: 然后在调用函数中:

result = hit(player, dealer);
player = result[0];
dealer = result[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM