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

JavaScript中rockPaperScissors函数返回值未在控制台显示问题排查

问题分析与解决:函数返回值未显示及代码错误修正

核心问题:函数返回值未被输出到控制台

你调用rockPaperScissors(userInput, pcChoice)时,只是执行了函数,但没有将返回值打印到控制台。return语句仅让函数返回结果,不会自动输出,必须主动用console.log()处理返回值才能在控制台看到内容。

代码中的其他错误

  • 逻辑运算符误用:你用了&(按位与运算符)做逻辑判断,正确的逻辑与运算符应该是&&。虽然&在部分场景下可能得到正确结果,但不符合逻辑判断的语义,容易引发潜在问题。
  • 失败分支信息错误:最后else分支里,返回的You won! ${pc} beats ${user}完全矛盾,应该改为表示失败的提示文本。

修复后的完整代码

let playerScore = 0;
let computerScore = 0;

let pcChoice = Math.floor(Math.random() * 3) + 1;
if (pcChoice === 1) {
  pcChoice = "rock";
} else if (pcChoice === 2) {
  pcChoice = "paper";
} else {
  pcChoice = "scissors";
}

let userInput = prompt("Rock ?\nPaper?\nScissors?")
userInput = userInput.toLowerCase();
let errorMessage = "You have put a wrong input"
if (!((userInput === "rock") || (userInput === "paper") || (userInput === "scissors"))) {
  alert(errorMessage);
} else {
  // 接收函数返回值并打印到控制台
  const gameResult = rockPaperScissors(userInput, pcChoice);
  console.log(gameResult);
  console.log("Userscore is " + playerScore + " and Computerscore is " + computerScore);
};

if (playerScore > computerScore) {
  console.log("You are the winner");
} else if (computerScore > playerScore) {
  console.log("Computer is the winner");
} else {
  console.log("It's a draw");
}

function rockPaperScissors(user, pc) {
  let winningMessage = "You Won!";
  let drawMessage = "it's a draw!";
  let losingMessage = "You lost!";
  // 修正逻辑与运算符为&&
  if (user === "rock" && pc === "scissors") {
    playerScore++;
    return `You won! ${user} beats ${pc}`;
  } else if (user === "paper" && pc === "rock") {
    playerScore++;
    return `You won! ${user} beats ${pc}`;
  } else if (user === "scissors" && pc === "paper") {
    playerScore++;
    return `You won! ${user} beats ${pc}`;
  } else if (user === pc) {
    return drawMessage;
  } else {
    computerScore++;
    // 修正失败提示信息
    return `${losingMessage} ${pc} beats ${user}`;
  }
}

关键修复点总结

  1. 调用函数时接收返回值,并用console.log()打印,才能在控制台看到函数返回的结果;
  2. 逻辑判断统一使用&&替代&,符合JavaScript逻辑运算的规范;
  3. 修正失败分支的提示文本,保证语义正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:36:31