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

JavaScript条件逻辑训练营任务报错:无效时间未返回null

解决JavaScript条件逻辑任务的测试失败问题

问题概述

参加训练营入门挑战,卡在一项JavaScript条件逻辑任务上,代码通过了10项测试中的9项,但有1项失败。

任务规则

  • 时间段判断:
    • 0≤time<12:早晨
    • 12≤time<24:傍晚
    • 其他时间(time<0 或 time≥24):greeting必须为null
  • 国家对应问候语:
    • 西班牙/墨西哥:早晨返回'buenos dias',傍晚返回'buenas noches'
    • 法国:早晨返回'bon matin',傍晚返回'bon soir'
    • 其他国家:greeting始终为null

当前代码

function sayHello(country, time) {
  let greeting = null

  switch (country) {
    case 'Mexico':
      if (time < 12) {
        greeting = 'buenos dias';
      } else if (time < 24) {
        greeting = 'buenas noches';
      }
      break;
    case 'Spain':
      if (time < 12) {
        greeting = 'buenos dias';
      } else if (time < 24) {
        greeting = 'buenas noches';
      }
      break;

    case 'France':
      if (time < 12) {
        greeting = 'bon matin';
      } else if (time < 24) {
        greeting = 'bon soir';
      }
      break;
    default:
      greeting = null;
  }
  // Don't change code below this line
  return greeting;
}

错误详情

当墨西哥地区传入无效时间(比如负数或≥24的数值)时,greeting应为null,但实际返回'buenos dias',触发AssertionError。

问题原因与修复

原因

当前代码中,判断早晨的条件仅检查time < 12,当time为负数时,这个条件会成立,错误地赋值早晨问候语,违反了“无效时间返回null”的规则。

修复方案

在每个国家的case中,给时间段判断加上有效范围的限制:

  • 早晨需同时满足time >= 0 && time < 12
  • 傍晚需同时满足time >= 12 && time < 24
  • 不满足这两个条件时,保持greeting为初始的null

修复后代码

function sayHello(country, time) {
  let greeting = null

  switch (country) {
    case 'Mexico':
    case 'Spain':
      // 合并相同逻辑的case减少冗余
      if (time >= 0 && time < 12) {
        greeting = 'buenos dias';
      } else if (time >= 12 && time < 24) {
        greeting = 'buenas noches';
      }
      break;
    case 'France':
      if (time >= 0 && time < 12) {
        greeting = 'bon matin';
      } else if (time >= 12 && time < 24) {
        greeting = 'bon soir';
      }
      break;
    default:
      greeting = null;
  }
  // Don't change code below this line
  return greeting;
}

注:将墨西哥和西班牙的case合并,减少重复代码,逻辑保持一致。

内容的提问来源于stack exchange,提问作者D_Ornellas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:07:32