我在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 Choice
或1
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>