我是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);
答案 0 :(得分:1)
您应该使用else without statement
或else 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
。
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;
如果替代方案只是反向检查,那么您可以省略第二次检查,因为
(numHours >= 8) === !(numHours < 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));
&#13;