很抱歉,如果该标题不清楚,请解释一下。
我正在使用Codecademy.com自学JavaScript
我正在使用if / else语句学习函数,并使用return生成结果而不是像我习惯的那样生成console.log。
无论如何,我在培训的这一点上写的代码是......
var sleepCheck = function(numHours)
{
if (sleepCheck >= 8);
return "You're getting plenty of sleep! Maybe even too much";
};
else
{
return "Get some more shut eye!";
}
sleepCheck(10);
sleepCheck(5);
sleepCheck(8);
所以我不知道我做错了什么。该代码返回一条红色错误消息,说
“SyntaxError:意外的标记'else'”
所以我知道它显然是在“其他”部分,但我不确定如何。
我遇到过这个网站,所以我需要一些帮助。如果你能,它将非常感激。谢谢!
答案 0 :(得分:1)
将您的JavaScript更改为以下内容:
var sleepCheck = function (numHours) {
if (numHours >= 8) {
return "You're getting plenty of sleep! Maybe even too much";
}
else {
return "Get some more shut eye!";
}
}
console.log(sleepCheck(10));
console.log(sleepCheck(5));
console.log(sleepCheck(8));
说明强>
语法存在多个问题,当不在代码行的末尾时使用;
而是在if语句的结尾处使用if
。 else
和numHours
逻辑也存在一些问题。同样在函数内部你应该使用sleepCheck
,因为它是函数的参数,而//This line is perfect
var sleepCheck = function(numHours)
{
//This line shouldn't end in a ; as it is invalid syntax you are opening an if also should use the function parameter of numHours not sleepCheck
if (sleepCheck >= 8);
//this line isn't reached because of the above error there isn't an error here
return "You're getting plenty of sleep! Maybe even too much";
//This also doesn't need to have a ; and shouldn't be closing the } as you are ending the function here
};
//This is now ignored because of the above but is good, doesn't line up with the above if because of the }; which should just be a }
else
{
//All good
return "Get some more shut eye!";
}
sleepCheck(10);
sleepCheck(5);
sleepCheck(8);
是函数本身,使用起来没有意义。
注意:我在3函数调用中使用了console.log来简化调试。您可以随意调用该功能。
详细错误
{{1}}
答案 1 :(得分:0)
if
语句末尾的分号表示语句已完成。摆脱它(第5行的那个),它应该工作。
答案 2 :(得分:0)
我使用'else if'因为在说明中说 否则(否则)如果睡眠小时数小于8,请让计算机返回“多闭眼!”; 所以我认为我需要。虽然有用。 耸肩
var sleepCheck = function (numHours) {
if (numHours >= 8) {
return "You're getting plenty of sleep! Maybe even too much!";
}
else if (numHours < 8) {
return "Get some more shut eye!";
}
};
console.log(sleepCheck(10));
console.log(sleepCheck(5));
console.log(sleepCheck(8));
答案 3 :(得分:0)
你需要在if语句后删除分号:if(sleepCheck&gt; = 8); &LT; ---
这是一个值得注意的有用规则:
在JavaScript中,永远不要在左大括号或开括号之前放置分号,因为它会使解析器跳过后面的代码块。
答案 4 :(得分:0)
以上解决方案均不适合我。这是一个真正有用的:\
var sleepCheck = function (numHours) {
if(numHours >= 8) {
return "You're getting plenty of sleep! Maybe even too much!";
} else
{
return "Get some more shut eye!";
}
};
sleepCheck(10);
sleepCheck(5);
sleepCheck(8);
在第3行和第5行,删除分号。它们导致您的else语法错误。确保在第9行包含分号,以根据Code Academy课程中的说明结束该功能。