我刷新它时有时无法加载页面

时间:2018-01-07 10:41:17

标签: javascript function

我正在做一个简单的摇滚,纸张,剪刀游戏。有时当我刷新页面时没有任何反应。发生这种情况时,不会显示任何错误。我尝试在像w3schools这样的在线编辑器上运行此代码,但结果是一样的。可能导致这个问题的原因是什么?

这是我的代码:

<body onload="game()">
    <script>
        function game(playerItem, computerSelection) {
        
            function computerSelection() {
                var arr = ["rock", "paper", "scissors"];
                var computerSelection = arr[Math.floor(Math.random() * 3)];
                return computerSelection;
            }
        
            var playerItem = "rock";
        
            if (playerItem == "rock" & computerSelection() == "paper") {
                document.write(rockVSpaper);
                return;
            };
            if (playerItem == "rock" & computerSelection() == "scissors") {
                document.write(rockVSscissors);
                return;
            };
            if (playerItem == "rock" & computerSelection() == "rock") {
                document.write(rockVSrock);
                return;
            };
        }
        var rockVSpaper = "You lose! The computer's paper wraps your rock.";
        var rockVSscissors = "You won! Your rock make the computer's scissors blunt.";
        var rockVSrock = "Tie! A Rock doesn't do anything with another rock.";
    </script>
</body>

1 个答案:

答案 0 :(得分:3)

它有时无效,因为您在computerSelection()语句条件下运行了if三次。这意味着每次检查时,您都会生成一个新的随机计算机选择,这意味着所有三个if条件都等于false

要解决此问题,您应该运行computerSelection()一次并将其生成的内容存储在变量中,然后在if语句中使用它。像这样:

var playerItem = "rock";
var computerItem = computerSelection();

if (playerItem == "rock" && computerItem == "paper") {
    document.write(rockVSpaper);
    return;
};
// The rest of the if statements and code...

在应用上述修改后,这是codepen