if else在javascript中调整函数内部

时间:2017-02-08 07:33:12

标签: javascript

我是javascript的新手,我的代码如下。根据条件代码应打印"更多关闭眼睛!"但是显示语法错误,不知道错误在哪里。

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

2 个答案:

答案 0 :(得分:1)

您应该使用else without statementelse if作为else(number of sleep < 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!";
  }
}
sleepCheck(10);

<强>否则

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

答案 1 :(得分:0)

如果

你需要另一个
} else if (numHours < 8) {
//     ^^                   if missing
//        ^^^^^^^^^         wrong variable name, with spaces

正确使用变量名称

numHours

而不是number of sleep

&#13;
&#13;
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));
&#13;
&#13;
&#13;

如果替代方案只是反向检查,那么您可以省略第二次检查,因为

(numHours >= 8) === !(numHours < 8)

&#13;
&#13;
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));
&#13;
&#13;
&#13;