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

JavaScript石头剪刀布小游戏prompt校验弹窗重复弹出原因求解

问题触发原因

你的问题核心出在while循环的判断条件逻辑错误:

  • 你使用了逻辑或||作为多条件的连接符,而这个场景下应该使用逻辑与&&
  • 逻辑或的规则是只要任意一个条件成立,整个判断结果就为真。当你第一次输入合法值比如rock时,captureUserInput !== Paper和captureUserInput !== Scissors这两个条件都成立,所以整个while条件判断结果为真,会直接进入循环弹出第二次输入框。
  • 额外的小问题:你第一次获取输入后调用了toLowerCase()做了小写转换,但是循环内获取的输入没有做小写处理,用户如果输入大写的Rock这类值会被判定为非法。
修正后的代码示例
const Rock = "rock";
const Paper = "paper";
const Scissors = "scissors";

const userInput = () => {
  const askingQuestion =
    "请从以下选项中选择:石头(Rock)、剪刀(Scissors)、布(Paper)";
  let captureUserInput = prompt(askingQuestion).toLowerCase();
  // 把||改成&&,表示只要不是三个合法值中的任意一个,就继续循环要求输入
  while (
    captureUserInput !== Rock &&
    captureUserInput !== Paper &&
    captureUserInput !== Scissors
  ) {
    captureUserInput = prompt(askingQuestion).toLowerCase();
  }
  // 跳出循环后统一输出结果即可
  document.write(`输入有效!你选择的是${captureUserInput}`);
};

const computerInput = () => {
  const computerChoice = Math.floor(Math.random() * 3);
  console.log(computerChoice);
};

userInput();
computerInput();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 19:45:01