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

石头剪刀布游戏中逻辑或运算符(OR)的正确使用问题

石头剪刀布游戏中逻辑或运算符(OR)的正确使用问题

嗨,别担心,刚入门编程遇到这种逻辑问题太正常啦!我来帮你拆解一下代码里的问题~

你遇到的核心问题是逻辑或运算符||的用法写错了。在JavaScript中,userInput === 'paper' || 'rock' || 'scissors'这个表达式的逻辑并不是你预期的“判断userInput是否等于paper、rock或者scissors其中之一”。

具体来说,||会逐个判断每个操作数的布尔值:

  • 第一个操作数userInput === 'paper'会返回true或false
  • 但后面的'rock'和'scissors'都是非空字符串,在JavaScript里会被直接判定为true
    所以不管你的输入是什么,整个条件表达式都会是true,函数自然会直接返回转成小写的输入值,根本不会走到else分支的错误提示。

正确的写法有两种:

  1. 完整写出每个判断条件:
const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if (userInput === 'paper' || userInput === 'rock' || userInput === 'scissors') {
    return userInput;
  } else {
    console.log(`Error: ${userInput} does not match.`);
    // 建议这里返回一个明确的值,比如null,保证函数返回一致性
    return null;
  }
}
  1. 用数组的includes方法(更简洁易读):
const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  const validChoices = ['paper', 'rock', 'scissors'];
  if (validChoices.includes(userInput)) {
    return userInput;
  } else {
    console.log(`Error: ${userInput} does not match.`);
    return null;
  }
}

测试一下修改后的代码,输入'Dog'就会正常输出错误提示,不会返回dog啦~另外你原来代码里定义的paper和rock常量没用到,可以删掉,或者用来构建validChoices数组,这样代码更规范。

备注:内容来源于stack exchange,提问作者Matthew Piwko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 13:44:37