SyntaxError:意外的令牌{

时间:2016-08-15 09:53:53

标签: javascript

为什么我一直收到此错误:我的代码中有SyntaxError: Unexpected token {

var sleepCheck = function(numHours) { 

    if (numHours >= 8) {
    return "You're getting plenty of sleep! Maybe even too much!"; 
    }

    else (numHours < 8 ) {
        return "Get some more shut eye!";
    };
}
console.log(sleepCheck(10));
console.log(sleepCheck(5));
console.log(sleepCheck(8));

2 个答案:

答案 0 :(得分:3)

typo错误:在if [if...else]

之后遗失else

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

注意:如果您没有任何其他条件,则if(...)条件之后不需要else部分(如评论中所述)

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

答案 1 :(得分: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!";
  };
}
console.log(sleepCheck(10));
console.log(sleepCheck(5));
console.log(sleepCheck(8));