我正在为“奥丁项目”创建一个石头剪刀布游戏。指令说明通过使用外部函数在一轮函数中实现计算机选择随机化来创建一轮游戏。为了练习,我试图将一个函数分配给变量名“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)
第一个变量是字符串,第二个是函数。他们永远不会平等。看起来您打算执行它并将其结果传递给playRound:
console.log(playRound('rock', computerChoice()));
或者,您必须在 playRound. 也许是这样的:
function playRound(playerSelection, computerSelection) {
let computerSelectionResult = computerSelection();
if (playerSelection === computerSelectionResult) {
//...
}
}
添加回答
举报
0/150
提交
取消