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

JavaScript石头剪刀布开发报错:toLowercase is not a function

Hey there! Let's fix that type error: toLowercase is not a function issue you're hitting with your rock-paper-scissors game. Here's what's going on and how to fix it:

1. The #1 Culprit: A Simple Typo!

You’ve got a tiny spelling mistake that’s causing the whole error—JavaScript’s string method for lowercasing is toLowerCase() (note the uppercase C at the end), not toLowercase() (lowercase c). This is super common for new JS devs since camelCase can trip you up, but fixing that spelling will immediately resolve the "not a function" error.

2. Bonus: Make Sure Your Input Is Actually a String

Even with the correct method name, you might hit this error if your user input isn’t a string. For example, if a user clicks "Cancel" on a prompt() dialog, it returns null—and you can’t call string methods on null. So we should add checks to handle empty inputs or invalid values too.

Full Working Game Code

Here’s a complete, error-handled version of your rock-paper-scissors game that fixes the lowercase issue and validates user input:

// Get user input
let userInput = prompt("Enter rock, paper, or scissors to play:");

// First, handle cases where user cancels or enters nothing
if (!userInput) {
  alert("You need to pick a choice! Let's try again.");
} else {
  // Convert input to lowercase with the CORRECT method
  let userChoice = userInput.toLowerCase();
  
  // Validate the input is one of the allowed options
  const validChoices = ["rock", "paper", "scissors"];
  if (!validChoices.includes(userChoice)) {
    alert(`"${userInput}" isn't a valid choice. Please enter rock, paper, or scissors.`);
  } else {
    // Generate computer's random choice
    const computerChoice = validChoices[Math.floor(Math.random() * validChoices.length)];
    
    // Figure out who wins
    let result;
    if (userChoice === computerChoice) {
      result = "It's a tie!";
    } else if (
      (userChoice === "rock" && computerChoice === "scissors") ||
      (userChoice === "paper" && computerChoice === "rock") ||
      (userChoice === "scissors" && computerChoice === "paper")
    ) {
      result = `You win! ${userChoice} beats ${computerChoice}.`;
    } else {
      result = `You lose! ${computerChoice} beats ${userChoice}.`;
    }
    
    // Show the final result
    alert(result);
  }
}
Quick Recap
  • Always double-check camelCase method names: toLowerCase() is the correct way to lowercase strings in JS.
  • Never trust user input blindly—add checks to handle empty values and invalid choices to avoid unexpected errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:45:10