繁体   English   中英

我的 JavaScript function 不起作用 - 尝试比较两个函数并在第二个 function 中返回一个语句

[英]My JavaScript function is not working - Trying to compare two functions and return a statement within the 2nd function

嘿 StackOverflow 社区!

我是新来的,刚开始通过 Odin Project 学习 JS。 我正在进行我的第一个 JS 项目(石头、纸、剪刀应用程序)并且卡住了....

我将在下面总结我的意图,然后是我的代码。

//用户将输入一个石头、纸或剪刀的值

//有了用户值,会和电脑随机选择的值进行比较

//根据用户输入和计算机生成的比较,将给出返回语句

几乎尝试了所有方法,但不确定如何继续前进。 请帮忙。

    function computerPlay() {
        let gameOptions = ['rock', 'paper', 'scissors'];
        const gameChoice = Math.floor(Math.random() * gameOptions.length);

        console.log(gameChoice, gameOptions[gameChoice]);
    }

    

    
    function playRound(playerSelection,computerSelection){

        
        
        if(playerSelection === 'rock' && computerSelection === 'paper') {
            return console.log('You lose! Paper beats rock.');
        }else if(playerSelection === 'paper' && computerSelection === 'scissors') {
            return console.log('You lose! Scissors beats paper.');
        }else if(playerSelection === 'scissors' &&  computerSelection === 'rock') {
            return console.log('You lose! Rock beats scissors');
        }else if(playerSelection === 'rock' && computerSelection === 'rock') {
            return console.log('Its a draw!');
        }else if(playerSelection === 'paper' && computerSelection === 'paper') {
            return console.log('Its a draw!');
        }else if(playerSelection === 'scissors' && computerSelection === 'scissors') {
            return console.log('Its a draw!');
        }else if(playerSelection === 'paper' && computerSelection === 'rock') {
            return console.log('You win!')
        }else if(playerSelection === 'rock' && computerSelection === 'scissors') {
            return console.log('You win!')
        }else {
            return console.log('You win!')
        }
        
    }
    
    
        const playerSelection = prompt('Choose either rock, paper, or scissors', '');
        const computerSelection = computerPlay();

        console.log(playRound(playerSelection, computerSelection));

我希望第二个 function 中的条件语句能够做到这一点。 仍在尝试围绕函数、参数和 arguments 进行思考。

任何和所有的帮助将不胜感激。! 谢谢。

computerPlay()不返回任何值。 所以computerSelection将是未定义的。

另外,更改此行console.log(playRound(playerSelection, computerSelection)); 只是playRound(playerSelection, computerSelection); 并从playRound()中删除return语句。

此外,您的逻辑可以大大简化。 例如if (playerSelection === computerSelection) console.log("It's a draw");

computerPlay function 不返回任何值。 我认为你应该在 playRound 之前控制每个值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM