Project Odin - Web开发101基础篇2:Snarky Robot练习代码问题求助
Hey there! Let's get your Snarky Robot up and running—hitting snags on beginner exercises is totally normal, so no need to feel stuck!
First, let's recap the exercise requirements to make sure we're on the same page:
询问用户最喜欢的数字,并按规则响应:若数字为42,回复“Yay! That’s my favorite too!”;若数字小于42,回复“Eh, that’s OK but X would be even better”
Since you said your code isn't working, here are some common pitfalls to check first:
1. 输入没有转换成数字
When you use prompt() to get user input, it returns a string—not a number. If you try to compare a string directly to 42 (like userInput < 42), the logic will break. Fix this by converting the input to a number first:
const favoriteNum = Number(prompt("What's your favorite number?")); // 或者用 parseInt():const favoriteNum = parseInt(prompt("..."), 10);
2. 条件判断语法错误
Double-check your if/else structure for typos:
- Did you use
=(assignment) instead of===/==(comparison)? That's a super common mistake! - Did you forget curly braces
{}around your response code? - Did you mix up the order of your conditions?
Here's a working example of the core logic to reference:
if (favoriteNum === 42) { alert("Yay! That’s my favorite too!"); } else if (favoriteNum < 42) { alert("Eh, that’s OK but 42 would be even better"); }
3. 未处理无效输入
What if the user types a word instead of a number? Your code might throw an error or behave weirdly. Add a quick check to handle this:
if (isNaN(favoriteNum)) { alert("Whoa, that's not a real number! Try again."); }
If you've gone through all these checks and still have issues, share your full code snippet (even if you think it's messy!)—we can spot the exact problem right away.
内容的提问来源于stack exchange,提问作者Nikhil Patel

