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

编程新手求助: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 yes and no parameters in your dogHuman function aren't being used (you're not passing values when calling dogHuman() anyway). We can remove them and just compare directly to the strings "yes" and "no".
  • Out-of-Order Calculation: You're trying to calculate humanAge before the user even inputs dogAge—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 convert dogAge to 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 let instead of var because let has 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 09:57:55