Javascript 使用带有返回和If/Else语句的函数

Javascript 使用带有返回和If/Else语句的函数,javascript,function,return,Javascript,Function,Return,对不起,如果标题不清楚,让我解释一下 我正在使用Codecademy.com自学JavaScript 我正在学习使用if/else语句的函数,并使用返回来生成结果,而不是像我习惯的那样使用console.log 不管怎样,我在训练中写的代码是 var sleepCheck = function(numHours) { if (sleepCheck >= 8); return "You're getting plenty of sleep! Maybe even too m

对不起,如果标题不清楚,让我解释一下

我正在使用Codecademy.com自学JavaScript

我正在学习使用if/else语句的函数,并使用返回来生成结果,而不是像我习惯的那样使用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'”

所以我知道,很明显,是在“其他”部分,但我不知道怎么做


我发现了这个网站,所以我需要一些帮助。如果可以,我将不胜感激。谢谢大家!

if语句末尾的分号表示该语句已完成。摆脱它(第5行的那一个),它应该会工作

将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));
说明:

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
是函数本身,使用起来没有意义

注意:我在3函数调用中使用了console.log以简化调试。您可以任意调用该函数

详细错误

//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);

我使用了“else if”,因为它在说明中说 否则(否则)如果睡眠时间少于8小时,让计算机返回“多睡一会儿!”所以我认为我需要。但它起了作用。耸耸肩

var sleepCheck=函数(numHours){
如果(numHours>=8){
return“你睡得很饱!可能睡得太多了!”;
}
否则如果(numHours<8){
return“多睡一会儿!”;
}
};
控制台日志(睡眠检查(10));
控制台日志(睡眠检查(5));
控制台日志(睡眠检查(8));

您需要删除if语句后面的分号:if(sleepCheck>=8) 上述解决方案对我都不起作用。以下是一个真正有效的方法:\

var sleepCheck=函数(numHours){
如果(numHours>=8){
return“你睡得很饱!可能睡得太多了!”;
}否则
{
return“多睡一会儿!”;
}
};
睡眠检查(10);
睡眠检查(5);

睡眠检查(8)仍然无法工作。现在它说,“应该是一个标识符,而不是另一个。”提醒我在使用ipad时不要麻烦回答问题:)否则在这种情况下也会做同样的事情,除非numHours不是一个数字,因此不能
大于等于
小于
,所以在这种情况下它不会做任何事情