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

JavaScript基础if条件判断问题:石头剪刀布play函数返回随机值

问题描述

我是编程新手,正在完成Odin Project的石头剪刀布练习,需要对比用户选择与机器选择,但play()函数出现问题,总是返回随机结果。我已尝试排查问题,甚至参考了他人的相关代码片段(仅该部分,未参考整个练习),但仍无法找到问题所在。以下是我的代码:

let userChoice = prompt("Choose your weapon: rock, paper or scissors").toLowerCase();
console.log(userChoice);


function getMachineChoice() {
  let values = ["rock", "paper", "scissors"];
  let randomValue = values[Math.floor(Math.random() * values.length)];
  return randomValue;
}
console.log(getMachineChoice());

let machineChoice = getMachineChoice();

function play(userChoice, machineChoice) {
  if (userChoice === machineChoice) {
    return "Its a tie!";
  } else if (userChoice === "rock" && machineChoice === "scissors") {
    return "You win!";
  } else if (userChoice === "paper" && machineChoice === "rock") {
    return "You win!";
  } else if (userChoice === "scissors" && machineChoice === "paper") {
    return "You win!";
  } else {
    return "You lose!";
  }
}
console.log(play(userChoice, machineChoice));
问题原因与修复

代码的问题不是play()函数逻辑出错,而是机器选择的生成不一致:

  • 你先调用了一次console.log(getMachineChoice()),这里生成了一个随机的机器选择并打印出来
  • 之后又调用getMachineChoice()赋值给machineChoice,这又生成了一个全新的随机值
  • 控制台打印的机器选择和实际传给play()函数的机器选择根本不是同一个,导致你误以为play()函数返回随机结果

修复方法很简单,先获取机器选择并赋值,再打印这个变量,不要重复调用getMachineChoice():

修改后的代码:

let userChoice = prompt("Choose your weapon: rock, paper or scissors").toLowerCase();
console.log(userChoice);


function getMachineChoice() {
  let values = ["rock", "paper", "scissors"];
  let randomValue = values[Math.floor(Math.random() * values.length)];
  return randomValue;
}

// 先获取机器选择并存储
let machineChoice = getMachineChoice();
// 打印存储好的机器选择,而非重新调用函数
console.log(machineChoice);

function play(userChoice, machineChoice) {
  if (userChoice === machineChoice) {
    return "Its a tie!";
  } else if (userChoice === "rock" && machineChoice === "scissors") {
    return "You win!";
  } else if (userChoice === "paper" && machineChoice === "rock") {
    return "You win!";
  } else if (userChoice === "scissors" && machineChoice === "paper") {
    return "You win!";
  } else {
    return "You lose!";
  }
}
console.log(play(userChoice, machineChoice));

这样控制台打印的机器选择和参与比较的机器选择是同一个,play()函数的结果就会符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:03:37