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:
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.
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.
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); } }
- 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

