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

如何为石头剪刀布JS代码添加格式标签并修复优化?

Hey there! Let's spruce up your Rock-Paper-Scissors code with proper HTML formatting, fix hidden bugs, and share some optimization tips to make it more robust.

Modified Code with HTML Formatting & Bug Fixes

// Get user input (normalized to uppercase to avoid case sensitivity issues)
var userChoice = prompt('Choose between Rock, Paper or Scissors').toUpperCase();
var computerChoiceArray = ['ROCK', 'PAPER', 'SCISSORS'];
var choiceNumber = Math.floor(Math.random() * 3);
var compChoice = computerChoiceArray[choiceNumber];

// Add HTML formatting for cleaner output
document.write('<h3>Rock-Paper-Scissors Result</h3>');
document.write('<hr>'); // Horizontal separator to split sections
document.write('<p>You chose: ' + userChoice + '</p>');
document.write('<p>Computer chose: ' + compChoice + '</p>');
document.write('<hr>');

var game = function(compChoice, userChoice) {
    // Validate input first to catch invalid entries early
    if (!computerChoiceArray.includes(userChoice)) {
        document.write('<p style="color: red;">Error: "' + userChoice + '" is not a valid choice! Please pick Rock, Paper, or Scissors.</p>');
        return;
    }

    if (compChoice === userChoice) {
        document.write('<p>The result is a <strong>Tie!!</strong></p>');
    } 
    // Group computer-win conditions for cleaner logic
    else if (
        (compChoice === "ROCK" && userChoice === "SCISSORS") ||
        (compChoice === "SCISSORS" && userChoice === "PAPER") ||
        (compChoice === "PAPER" && userChoice === "ROCK")
    ) {
        document.write('<p>Computer wins !!!</p>');
    } else {
        document.write('<p>You won !!!</p>');
    }
}

game(compChoice, userChoice);

Key Changes & Explanations:

  1. HTML Formatting Additions

    • Added <h3> for a clear, readable title
    • Used <hr> to create visual separators between the title, choices, and result
    • Wrapped all output text in <p> tags to ensure proper paragraph spacing (instead of plain text running together)
    • Used <strong> to emphasize the tie result for better visual hierarchy
  2. Critical Bug Fixes

    • Fixed the trailing space in "Rock " (original code had an extra space that broke comparisons if the user input didn't match it exactly)
    • Normalized both user and computer choices to uppercase with .toUpperCase()—this eliminates issues where the user types "rock" (lowercase) instead of "Rock"
    • Improved input validation to check if the user's choice exists in the valid options array, so invalid entries are caught immediately
  3. Code Optimization Tips

    • Simplify Win/Lose Logic: Replaced the long chain of else if statements with a single block grouping all computer-win conditions using logical OR (||)—this makes the code shorter and easier to maintain
    • Early Exit for Invalid Input: We check for invalid choices at the start of the game function, so we don't waste time running through unnecessary win/lose checks
    • Avoid document.write (Optional Upgrade): For more modern code, use document.getElementById to update a specific HTML element instead of document.write (which can overwrite the entire page if called after page load). Example:
      // Add this div to your HTML first: <div id="game-result"></div>
      var resultDiv = document.getElementById('game-result');
      resultDiv.innerHTML = '<p>You chose: ' + userChoice + '</p>';
      
    • Descriptive Naming: Consider renaming variables like compChoice to computerChoice for better readability (especially if you plan to expand the code later)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:35:37