javascript - Javascript 中 undefined variable ,请帮助使其正确

标签 javascript oop error-handling

我正在编写一个基本的剪刀石头布游戏。

这两个功能运行良好。问题是获胜者变量始终未定义..

我不知道该怎么做才能纠正这个问题。我想让它说出谁赢了,计算机还是人类(用户)。

function game(x, y) {
    var inputC = computerPlay();
    var inputH = humanPlay();
    var winner;

    if (inputH == 'paper' && inputC == 'scissors') {
        console.log('Computer wins with Scissors ');

        if (inputH == 'scissors' && inputC == 'rock') {
            console.log('Computer wins with rock');

            if (inputC == 'paper' && inputH == 'rock') {
                console.log('Computer wins with paper');
            }
        }

        winner = "computer";
    } else if (inputC == 'paper' && inputH == 'scissors') {
        console.log('Human wins with Scissors ');

        if (inputC == 'scissors' && inputH == 'rock') {
            console.log('Human wins with rock');

            if (inputH == 'paper' && inputC == 'rock') {
                console.log('Human wins with paper');
            }
        }
        winner = "human";
    }
    document.getElementById("text1").innerHTML = winner;
    console.log("result is: " + winner + " wins");
}

我确信这只是小事,但天哪,我已经没有主意了。

最佳答案

想要这个

function game() {
    var inputC = computerPlay();
    var inputH = humanPlay();
    var winner = "human";

    if (inputH === inputC) {
       winner = "nobody";
    } else if ((inputH === 'paper' && inputC === 'scissors') ||
        (inputH === 'scissors' && inputC === 'rock') ||
        (inputH === 'rock' && inputC === 'paper')
    ) {
        console.log('Computer wins with ' + inputC);
        winner = "computer";
    } else {
        console.log('Human wins with ' + inputH);
    }

    document.getElementById("text1").innerHTML = winner;
    console.log("result is: " + winner + " wins");
}

关于javascript - Javascript 中 undefined variable ,请帮助使其正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433689/

相关文章:

javascript - 为 CSS 事物开发类似 FIrebug 的 Web 应用程序

python - 如何使用 Python 获取树的叶节点?

javascript - jQuery .slide 和 .slideUp。没开

javascript - 在 HTA 中单击时使按钮变色?

具有默认参数的 Python 类构造函数

web-applications - 如何设计/规划 Web 应用程序开发?

powershell - 使用PSSession时令人困惑的ErrorAction行为

python - “Rect argument is invalid”

validation - GraphQL 和表单验证错误

javascript - 无法配置 webpack.config 文件