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

时间:2015-09-05 19:06:31

标签: javascript function return

我正在进行自动(直到完成没有用户输入)二十一点游戏。

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

我对如何将playerdealer传递到点击功能并让他们将其值返回playerdealer感到困惑。现在很难将它们分开。

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

使用对象? 开始:

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

发布功能:

ob = {
  player: 18,
  dealer: 19
}

2 个答案:

答案 0 :(得分:1)

不,函数无法区分用于计算其参数的变量(或任何其他表达式)。它只能区分值。

对于您的情况,您应该考虑使用第二个参数与播放器名称(属性):

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

答案 1 :(得分:0)

为简单起见,您可以只返回两个项目的数组吗?

return [player, dealer];

然后在调用函数中:

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