codecademy“函数和; if / else”

时间:2014-02-08 18:31:43

标签: javascript

我似乎找不到为什么会返回错误的答案。关于代码学院这一部分的其他问题与丢失或错放的“{}”和丢失或错放的“;”有关。我不相信我遇到了这个问题,但它仍然会返回错误。

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

7 个答案:

答案 0 :(得分:5)

  1. sleepCheck是您将其用作变量的函数。
  2. 您需要使用传递给numHours条件
  3. 中的if参数

    代码

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

    DEMO

答案 1 :(得分:2)

在if语句中,您应该比较变量numHours,而不是现在正在比较的函数名sleepCheck

答案 2 :(得分:1)

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

说明:1>你应该比较变量numHours而不是名为sleepCheck的函数。

例如:

var time = function(number){
    return number*2
};

var newNumber = time(10);

console.log(newNumber); 

将打印出20

所以在这种情况下,没有人会使用"返回时间* 2",它没有意义。相反,他们使用"返回号码* 2"。与 if(numHours> = 8) if(sleepCheck> = 8)

相同的想法
2> is not "if (sleepCheck>8)", should be " if (numHours>=8)".

希望我现在能够帮助你理解。

答案 3 :(得分:1)

这是我解决它的方式。我在我的本地编辑器和控制台中工作,因此这个示例将在调用函数时为您提供所需的反馈。它应该满足Codeacademy参数。

function sleepCheck(numHours) {
  return numHours >= 8
  ? "You're getting plenty of sleep!  Maybe even too much" 
  : "Get some more shut eye!";
};

console.log(sleepCheck(10));
console.log(sleepCheck(5));
console.log(sleepCheck(8));

此考试使用inline conditional ternery operator。并非所有情况都需要它们,但有时你会发现它们的很多用途。 Using function

答案 4 :(得分:0)

sleepCheck是函数

  var sleepCheck = function (hrs)

     {

     if (hrs >= 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);

答案 5 :(得分:0)

function sleepCheck(numHours) {
    if (numHours >= 8) {
        return "You're getting plenty of sleep! Maybe even too much!";
    } else {
        return "Get some more shut eye!";
    }
}
sleepCheck(10);

答案 6 :(得分: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);

// this works now works on code academy as I added the correct symbol on if  numHours. however when copied and pasted make sure you get rid of anything before the first line of the actual code which starts with var. this sometimes appears in codeacademy when you paste the code.