You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codecademy if/else练习报Unexpected token else错误求解决

问题排查结果

报错原因

  • 语法层面:你的代码中isDividableBy400对应的if...else语句已经完整闭合,后续额外拼接的else { console.log("a leap year") }没有对应的匹配if,属于无效语法,直接触发Unexpected token else报错。
  • 逻辑层面:isDividableBy400变量仅在isDividableBy100 == true的代码块内部声明,若输入年份可被4整除但不可被100整除,后续访问isDividableBy400时会抛出变量未定义的运行时错误。

修正后代码

var year = prompt("Enter a year (ex: 2000)");
year = Number(year);

console.log("The year " + year + " is...");

var isDividableBy4 = isDividableBy(year, 4);

if (isDividableBy4 == true) {
  var isDividableBy100 = isDividableBy(year, 100);
  if (isDividableBy100 == true) {
    var isDividableBy400 = isDividableBy(year, 400);
    if (isDividableBy400 == true) {
      console.log("a leap year");
    } else {
      console.log("not a leap year");
    }
  } else {
    console.log("a leap year");
  }
} else {
  console.log("not a leap year");
}

可选优化建议

  • 布尔类型变量判断不需要额外写== true,直接使用变量本身作为判断条件即可,代码更简洁
  • 单个分支逻辑只有一行的场景,可以用三元运算符简化写法,减少冗余代码

内容的提问来源于stack exchange,提问作者Mohammad Shams Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:24:03