编程新手求助:JavaScript带参函数与动态变量开发(犬龄转人龄)
Fixing Your Dog-to-Human Age Calculator
Hey there! Let's walk through fixing your dog-to-human age calculator step by step—you're off to a great start, just a few tweaks needed to get it working smoothly.
Key Issues in Your Current Code
- Unnecessary Parameters: The
yesandnoparameters in yourdogHumanfunction aren't being used (you're not passing values when callingdogHuman()anyway). We can remove them and just compare directly to the strings"yes"and"no". - Out-of-Order Calculation: You're trying to calculate
humanAgebefore the user even inputsdogAge—this will throw a "dogAge is not defined" error. We need to move the calculation after getting the dog's age. - String-to-Number Conversion: User input from
prompt()comes as a string. If you try to do math with it, you'll get weird results (like string concatenation instead of addition). We need to convertdogAgeto a number first. - Input Validation Loop: Your current else branch just reprompts the user but doesn't re-check their answer. A loop will ensure we keep asking until they enter a valid "yes" or "no".
- Minor Typo: "Thank you for you attention" has a small spelling error—should be "your" instead of "you".
Revised Working Code
function dogHuman() { // Loop until user enters valid yes/no (case-insensitive) let haveDog; do { haveDog = prompt("Do you have a dog? yes or no").toLowerCase(); } while (haveDog !== "yes" && haveDog !== "no"); if (haveDog === "yes") { // Get dog age and convert to a number let dogAge = Number(prompt("How old is your dog? ")); // Calculate human age AFTER we have the dog's age let humanAge = ((dogAge - 2) * 4) + 21; alert(`If your dog were human, it would be ${humanAge} years old`); } else { alert("Thank you for your attention"); } } // Call the function to start the program dogHuman();
Extra Tips for Your Learning
- I used
letinstead ofvarbecauselethas block scope, which is more predictable in modern JavaScript (it prevents accidental variable leaks). - Added
.toLowerCase()to the input so the function accepts "Yes", "YES", or even "yEs"—making it more user-friendly. - Used template literals (backticks
`) in the alert to make the string easier to read—this is a cleaner alternative to string concatenation with+.
内容的提问来源于stack exchange,提问作者Delly
相关产品推荐
相关产品推荐

