You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的JavaScript石头剪刀布游戏if else语句存在什么问题?

石头剪刀布游戏问题修复

核心错误点

1. 玩家选择函数无返回值

getPlayerChoice函数调用prompt获取输入后,没有用return返回结果,导致playerSelection始终为undefined,前面所有条件判断都无法匹配,最终必然执行最后一段代码。

修复:给函数添加返回语句

function getPlayerChoice() {
    return prompt("rock paper or scissors?").toLowerCase();
}

2. 最后一个条件语法错误

你把else if错误写成了else (playerSelection === "scissors" && computerSelection === "paper") ;{...},这里的分号会强制断开else逻辑与后续代码块,不管条件是否成立,console.log("You win! Scissors beats Paper")都会执行。而且else后面不能直接跟条件,正确写法是使用else if。

修复:修正条件语法

else if (playerSelection === "scissors" && computerSelection === "paper") {
    console.log ("You win! Scissors beats Paper");
}

额外优化建议

playRound函数定义时接收了playerSelection和computerSelection参数,但内部直接重新赋值覆盖了参数,这两个参数完全冗余,可以直接去掉;同时用const声明变量更严谨。

完整修复代码

function getComputerChoice() {
    const randomNumber = Math.floor(Math.random()*3);
    switch(randomNumber) {
        case 0:
            return "rock";
        case 1: 
            return "paper";
        case 2:
            return "scissors";
    };
}

function getPlayerChoice() {
    return prompt("rock paper or scissors?").toLowerCase();
}

function playRound() {
    const computerSelection = getComputerChoice()
    const playerSelection = getPlayerChoice()

    if (computerSelection === playerSelection) {
        console.log("Tie");
    } else if (computerSelection === "rock" && playerSelection === "scissors") {
        console.log("You lose! Rock beats Scissors");
    } else if (computerSelection === "paper" && playerSelection === "rock") {
        console.log("You lose! Paper beats Rock");
    } else if (computerSelection === "scissors" && playerSelection === "paper") {
        console.log("You lose! Scissors beats Paper");
    } else if (playerSelection === "rock" && computerSelection === "scissors") {
        console.log("You win! Rock beats Scissors");
    } else if (playerSelection === "paper" && computerSelection === "rock") {
        console.log("You win! Paper beats Rock");
    } else if (playerSelection === "scissors" && computerSelection === "paper") {
        console.log("You win! Scissors beats Paper");
    } else {
        console.log("Invalid input! Please enter rock, paper, or scissors.");
    }
}

内容的提问来源于stack exchange,提问作者N3ttle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 06:45:00