【问题标题】:assigning function to variable and using in parameter does not work将函数分配给变量并在参数中使用不起作用
【发布时间】:2020-06-29 11:43:03
【问题描述】:

我正在为“奥丁计划”创建一个石头剪刀布游戏。指令说明创建一个一轮游戏,计算机选择随机化,通过使用外部函数在一轮函数中实现。

为了练习,我尝试将一个函数分配给变量名称“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!

【问题讨论】:

  • 我认为你应该调用计算机选择功能。

标签: javascript


【解决方案1】:

首先,您尝试为您的函数指定两个名称:

let computerChoice = function computerPlay() {
  //...
}

只要变量名就足够了:

let computerChoice = function () {
  //...
}

除此之外,您永远不会执行该函数。您已成功将其传递给 playRound 函数,但您只是尝试比较它:

if (playerSelection === computerSelection)

第一个变量是字符串,第二个是函数。他们永远不会平等。看起来您打算执行它并将其 result 传递给 playRound:

console.log(playRound('rock', computerChoice()));

或者,您必须在 playRound 执行它。也许是这样的:

function playRound(playerSelection, computerSelection) {
  let computerSelectionResult = computerSelection();

  if (playerSelection === computerSelectionResult) {
    //...
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多