为什么路径变量会丢失字符?

Why is path variable losing characters?

我有一个 API 路径,我需要在其中将月份显示为 2 位数字的日期。但是,它一直在删除左边的零。

例如,当我获取日期时,如果是一月到九月,它只有 returns 一位数字。所以我使用下面的代码来添加额外的零:

const date = new Date();
  const year = date.getFullYear();
  let month = date.getMonth();
  let path = ``;
  switch (month) {
    case (month < 10):
      month = `0${month}`;
      path = `/v2/reports/time/team?from=${year}0${month}01&to=${year}0${month}31`;
      break;
    default:
      path = `/v2/reports/time/team?from=${year}${month}01&to=${year}${month}31`;
      break;
  }

然而,当代码实际运行时,路径总是打印成这样(returns 一个错误,因为日期中月份前面的零被删除):

/v2/reports/time/team?from=2021701&to=2021731

应该是这样的:

/v2/reports/time/team?from=20210701&to=20210731

我错过了什么?

为什么不直接给变量加零呢?

const date = new Date();
const year = date.getFullYear();
let month = (date.getMonth() < 10) ? '0' + date.getMonth() : date.getMonth();
let path = `/v2/reports/time/team?from=${year}${month}01&to=${year}${month}31`;

console.log(path);

开关实现不正确,所以只有默认执行,我建议你先探索JavaScript中的开关,这对你以后也有帮助,

不过我修改了代码,请看下面

const date = new Date();
const year = date.getFullYear();
let month = date.getMonth();
let path = ``;
switch (true) {
  case month < 10:
    path = `/v2/reports/time/team?from=${year}0${month}01&to=${year}0${month}31`;
    break;
  default:
    path = `/v2/reports/time/team?from=${year}${month}01&to=${year}${month}31`;
    break;
}