夢里花落0921
2022-10-21 15:26:24
我正在為“奧丁項目”創建一個石頭剪刀布游戲。指令說明通過使用外部函數在一輪函數中實現計算機選擇隨機化來創建一輪游戲。為了練習,我試圖將一個函數分配給變量名“computerChoice”。當我這樣做時,它的結果是未定義的。如果我只是使用函數調用“computerPlay()”將我的參數放入 playRound(),它就可以工作。如果我為函數“computerChoice”使用分配的變量,它就不起作用。我在網上搜索了這個,據說你可以在 Javascript 中做到這一點。我在這里做錯了什么?let choices = ['rock', 'paper', 'scissors'];const rdm = Math.floor(Math.random() * 3);const computer = choices[rdm];// let playerSelection = playerSelection.toLowerCase();function playRound(playerSelection, computerSelection) { if (playerSelection === computerSelection) { return 'It is a tie!!!'; } else if (playerSelection === 'rock' && computerSelection === 'paper') { return 'PAPER BEATS ROCK! computer wins!' } else if (playerSelection === 'rock' && computerSelection === 'scissors') { return 'ROCK BEATS SCISSORS! player wins!'; } else if (playerSelection === 'paper' && computerSelection === 'scissors') { return 'SCISSORS BEATS PAPER! computer wins!' } else if (playerSelection === 'paper' && computerSelection === 'rock') { return 'PAPER BEATS ROCK! player wins!'; } else if (playerSelection === 'scissors' && computerSelection === 'rock') { return 'ROCK BEATS SCISSORS! computer wins!' } else if (playerSelection === 'scissors' && computerSelection === 'paper') { return 'SCISSORS BEATS PAPER! player wins!'; }}// function computerPlay() {// const computer = choices[rdm];// return computer;// }// console.log(playRound('rock', computerPlay())); // This works!let computerChoice = function computerPlay() { const computer = choices[rdm]; return computer;}console.log(playRound('rock', computerChoice)); // This does not Work!
1 回答

慕尼黑的夜晚無繁華
TA貢獻1864條經驗 獲得超6個贊
首先,你試圖給你的函數兩個名字:
let computerChoice = function computerPlay() {
//...
}
只要變量名就足夠了:
let computerChoice = function () {
//...
}
除此之外,您永遠不會執行該功能。您已成功將其傳遞給playRound函數,但隨后您只是嘗試比較它:
if (playerSelection === computerSelection)
第一個變量是字符串,第二個是函數。他們永遠不會平等??雌饋砟蛩銏绦兴⑵浣Y果傳遞給playRound:
console.log(playRound('rock', computerChoice()));
或者,您必須在 playRound. 也許是這樣的:
function playRound(playerSelection, computerSelection) {
let computerSelectionResult = computerSelection();
if (playerSelection === computerSelectionResult) {
//...
}
}
添加回答
舉報
0/150
提交
取消