当与提示功能结合使用时,switch语句始终执行默认情况

时间:2020-03-31 06:23:19

标签: javascript html switch-statement

我在HTML中编写了以下switch语句:

<script>
    const day = prompt("Enter day number: ");
    switch (day) {
        case 1:
            document.write("Sun");
            break;
        case 2:
            document.write("Mon");
            break;
        case 3:
            document.write("Tue");
            break;
        default:
            document.write("Wrong Choice");
    }
</script>

即使我通过Wrong Choice1

,以上语句也始终会生成输出2

2 个答案:

答案 0 :(得分:2)

prompt始终返回 string ,并将大小写与===进行比较-字符串不会是===到数字。将您的案例字符串改为:

const day = prompt("Enter day number: ");
switch (day) {
  case '1':
    document.write("Sun");
    break;
  case '2':
    document.write("Mon");
    break;
  case '3':
    document.write("Tue");
    break;
  default:
    document.write("Wrong Choice");
}

但是switch非常冗长,并且容易出错。考虑改用对象或数组:

const days = [, 'Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];

const dayNum = prompt("Enter day number: ");
const day = days[dayNum] || 'Invalid';
console.log(day);

答案 1 :(得分:0)

我猜这是作为字符串传递的。尝试做

   <script>
const day = prompt("Enter day number: ");
switch (day) {
    case ‘1’:
        document.write("Sun");
        break;
    case ‘2’:
        document.write("Mon");
        break;
    case ‘3’
        document.write("Tue");
        break;
    default:
        document.write("Wrong Choice");
}
</script>