[英]Variable declaration in switch-case statements in JavaScript
我创建了一个函数 day_of_week(dayy) 并在函数中使用了 switch-case 语句。
function day_of_week(dayy) {
var result;
switch (dayy) {
case 1:
result = "monday";
case 2:
result = "Tuesday";
case 3:
result = "wednesday";
case 4:
result = "thursday";
case 5:
result = "friday";
case 6:
result = "saturday";
case 7:
result = "sunday";
default:
result = "No day";
}
document.write(result);
}
document.getElementById("switch").innerHTML = day_of_week(1);
document.getElementById("switch").innerHTML = day_of_week(2);
实际上在 switch-case 语句中,如果没有“中断”,代码应该随机执行。 但是在这里,当我声明名为 result 的变量并在没有“中断”的情况下将 case 值分配给它时。 因此,代码应该随机执行所有案例而不会中断。 但是,这里的变量处于重新声明值并执行最后一种情况的实例下。 我无法知道我的错误是在声明变量还是使用 switch-case 语句以及所有在函数实例下。 请帮忙...
您的代码中没有 break 语句。 我希望这对你有用。
<!DOCTYPE html>
<html>
<head>
<script>
function day_of_week(dayy){
var result;
switch(dayy){
case 1: result = "Monday";
break;
case 2: result = "Tuesday";
break;
case 3: result = "wednesday";
break;
case 4: result = "Thursday";
break;
case 5: result = "Friday";
break;
case 6: result = "Saturday";
break;
case 7: result = "Sunday";
break;
default: result = "No day";
}
document.write(result);
}
document.getElementById("switch").innerHTML = day_of_week(2);
</script>
</head>
<body>
</body>
</html>
我会做这样的事情来获得随机的一天:
function getDay() {
const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
return days[Math.floor(Math.random() * 7)];
}
我使用 berak 和 Math 方法重构了这段代码
function day_of_week(day) {
var result;
switch (day) {
case 1:
result = "monday";
break;
case 2:
result = "Tuesday";
break;
case 3:
result = "wednesday";
break;
case 4:
result = "thursday";
break;
case 5:
result = "friday";
break;
case 6:
result = "saturday";
break;
case 7:
result = "sunday";
break;
default:
result = "No day";
}
document.write(result);
}
document.getElementById("switch").innerHTML = day_of_week(Math.floor( Math.random()*10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.