首页 > 解决方案 > 使用“switch”语句显示星期几。(问题)

问题描述

我遇到了显示一周中某一天的 switch 语句的问题。我想从用户那里获取输入(一个数字)并显示一周中的某一天。这是我的源代码,请指出我的功能有什么问题。

let clickButton = document.getElementById("button");
clickButton.addEventListener("click", function weekDay() {

  let day = Number(document.getElementById("numberDay").value);

  switch (day) {

    case 0:
      alert("It's Sunday!")
      break;
    case 1:
      alert("It's Monday");
      break;
    case 2:
      alert("It's Tuesday");
      break;
    case 3:
      alert("It's Wednesday");
      break;
    case 4:
      alert("It's Thursday");
      break;
    case 5:
      alert("It's Friday");
      break;
    case 6:
      alert("It's Saturday");
      break;

  }

})
Enter a number: <input type="text" id="numberDay">
<button id="button">OK</button>

标签: javascripthtmlswitch-statement

解决方案


你的代码看起来不错。但是,如果用户输入除了 0-6 数字之外的其他内容,您可能需要添加默认情况。也许为 7 号添加另一个案例以用于周日。

switch (day) {

    case 0:
    case 7:
      alert("It's Sunday!")
      break;
    case 1:
      alert("It's Monday");
      break;
    case 2:
      alert("It's Tuesday");
      break;
    case 3:
      alert("It's Wednesday");
      break;
    case 4:
      alert("It's Thursday");
      break;
    case 5:
      alert("It's Friday");
      break;
    case 6:
      alert("It's Saturday");
      break;
    default: 
      alert("Wrong input!");
      break;

  }

不妨将输入类型从更改textnumber

<input type="number" id="numberDay">

或者您是否遇到任何其他问题?


推荐阅读