首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >codeacademy if/else javascript

codeacademy if/else javascript
EN

Stack Overflow用户
提问于 2016-04-07 20:58:22
回答 5查看 222关注 0票数 4

我正在学习JS的CodeAcademy课程,但是有一个问题,脚本是有效的,但是我

代码语言:javascript
复制
console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'");
console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'");
var userAnswer = prompt("Do you want to race Bieber on stage?");

if(userAnswer === "yes") {
    console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!");
}
else {
    console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'");
}

给我错误信息:

代码语言:javascript
复制
Oops, try again. Did you add an if statement to your code?

在这里页面:https://www.codecademy.com/courses/javascript-beginner-en-x9DnD/0/5?curriculum_id=506324b3a7dffd00020bf661,它在你自己的冒险代码中!5.

EN

回答 5

Stack Overflow用户

发布于 2016-04-07 21:06:03

我猜它可能是Codeacadamey的一个bug。奇怪的是,下面的代码正常工作,并给我一个绿色的图标。

编写if、else if和else语句可以解决这些问题。这可能是因为说明不是很清楚。

代码语言:javascript
复制
// Check if the user is ready to play!
var userAnswer = prompt("Do you want to race Bieber on stage?");

if (userAnswer === 'yes') {
    console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!");
} else if (userAnswer === 'no') {
    console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'");
} else {
    console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'");
}
票数 2
EN

Stack Overflow用户

发布于 2016-04-07 21:02:57

您的代码可以在浏览器中运行,我可以在浏览器控制台窗口中看到结果,所以我认为您应该将此报告为bug。

但是,您只需要检查小写的yesYesYES将与if语句不匹配,并将运行else块中的代码。

您可以尝试:

代码语言:javascript
复制
if(userAnswer.toLowerCase() === "yes") {    
    // Your code here
} else {
    // Your code here
}
票数 0
EN

Stack Overflow用户

发布于 2016-04-07 21:14:49

有时,Codeacademy会根据微不足道的空格差异错误地报告代码中的错误。根据脚本的输出,您已经正确地编写了代码。

有趣的是,使用ternary operator而不是if语句可以很好地工作:

代码语言:javascript
复制
// Check if the user is ready to play!

console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'");
console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'");
var userAnswer = prompt("Do you want to race Bieber on stage?");

console.log( userAnswer === "yes" ?
    "You and Bieber start racing. It's neck and neck! You win by a shoelace!" :
    "Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'"
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36476936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档