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

新手编写石头剪刀布游戏输入rock时总是返回paper wins问题求助

问题原因与修复方案

核心错误点

  • 电脑出拳取值错误
    原代码行:let compChoice = [Math.floor(Math.random() * cChoice.length)];
    该行代码得到的是存放了随机数字索引的数组,而非你预期的rock/paper/scissor出拳字符串,和用户输入的字符串比较永远不匹配,当你输入rock时会始终进入else分支返回paper wins。
    正确写法:let compChoice = cChoice[Math.floor(Math.random() * cChoice.length)];
  • 平局逻辑不完整
    原平局判断分支仅弹出提示,没有终止函数执行,后续胜负判断逻辑会继续运行,出现同时弹平局提示又返回胜负结果的逻辑冲突,需要在平局分支增加return语句终止函数执行。

修复后完整代码

function game() {
  const pChoice = prompt('What is your play?');
  const cChoice = ['rock','paper','scissor'];
  
  // 修正电脑出拳取值逻辑
  const compChoice = cChoice[Math.floor(Math.random() * cChoice.length)];
  console.log('电脑出拳:', compChoice);

  function compare(pChoice, compChoice) {
    if (pChoice === compChoice) {
      alert( "It's a tie" );
      return "tie"; // 新增return终止函数执行
    }

    if (pChoice === 'rock') {
      if (compChoice === 'scissor') {
        return 'rock wins';
      } else {
        return 'paper wins';    
      }
    }
    else if (pChoice === 'paper') {
      if (compChoice === 'rock') {
        return 'paper wins';
      } else {
        return 'scissor wins';
      }
    }
    else if (pChoice === 'scissor') {
      if (compChoice === 'paper') {
        return 'scissor wins';
      } else {
        return 'rock wins';
      }
    }
  }

  const result = compare(pChoice, compChoice);
  console.log('对局结果:', result);
}

game();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:06:02