2015-09-05 16 views
0

我正在自動(運行,直到沒有用戶輸入)二十一點遊戲。如何區分傳入函數的變量?

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。現在很難將它們分開。

理想輸出:

$ 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 
} 
+1

我不明白的問題,但可以通過返回或者返回多個值一個對象或一個數組。 '返回{手:手,玩家:玩家};' – jfriend00

+0

我現在已經清理了一下,以更好地解釋我試圖走出去 –

+0

如果你想要一個函數來真正改變你傳入的變量,那麼唯一的方法是傳入一個對象,其中變量是對象上的屬性。然後,您可以更改對象的屬性,調用者也會看到這些更改(或者將變量設置爲全局或在父範圍內,但我認爲這不是您要求的)。 – jfriend00

回答

0

爲了簡單起見,你可以只歸還兩個項目組成的數組?

return [player, dealer]; 

然後在調用函數:

result = hit(player, dealer); 
player = result[0]; 
dealer = result[1]; 
+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");