我被赋予了一项任务,我自己几乎已经解决了 但 需要进行一些小的更正,我需要某人的帮助来指出我在哪里可以对我的代码进行一些外观更改:
这是任务:
将多条件if语句样例代码转化为switch样例代码。
var myAge = parseInt(prompt("Enter your age", 30), 10);
if (myAge >= 0 && myAge <= 10) {
document.write("myAge is between 0 and 10<br />");
}
if (!(myAge >= 0 && myAge <= 10)) {
document.write("myAge is NOT between 0 and 10<br />");
}
if (myAge >= 80 || myAge <= 10) {
document.write("myAge is 80 or above OR 10 or below<br />");
}
if ((myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89)) {
document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89");
}
<DOCTYPE html>
<html lang="en">
<head>
<title>SOME CODE</title>
</head>
<body>
</body>
</html>
所以 30 岁以下的默认结果是:
myAge is NOT between 0 and 10 myAge is between 30 and 39 or myAge is
between 80 and 89
这是我到目前为止所做的:
var myAge = parseInt(prompt("Enter your age", 30), 10); // Get the user's response, converted to a number
switch (true) { // Switch statement if the condition is True
case myAge >= 0 && myAge <= 10: // Check the inputs value in range 0 - 10
document.write("myAge is between 0 and 10<br/>");
break;
case (!(myAge >= 0 && myAge <= 10)): // Check the inputs value if it's not a in range between 0 - 10 ( !(myAge >= 0 && myAge <= 10) )
document.write("myAge is NOT between 0 and 10<br/>");
break;
case myAge >= 80 || myAge <= 10: // Check the inputs value if it's greater/equal to 80 OR less/equal to 10
document.write("myAge is 80 or above OR 10 or below<br/>");
break;
default:
document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89"); // Check the inputs value in range 30 - 39 And 80 - 89
}
<DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 3, Example 2</title>
</head>
<body>
</body>
</html>
而且,如您所见,结果略有不同。我只打印了这个:
myAge is NOT between 0 and 10
我知道解决方案很简单,但不幸的是我无法解决它,因此它会打印:
myAge is NOT between 0 and 10 myAge is between 30 and 39 or myAge is
还有。
请有人帮助我解决它,我真的很感激!
最佳答案
Nested Switch Case
var myAge = parseInt(prompt("Enter your age", 30), 10);
switch (true) {
case myAge >= 0 && myAge <= 10:
document.write("myAge is between 0 and 10<br/>");
default:
switch (true) {
case (!(myAge >= 0 && myAge <= 10)):
document.write("myAge is NOT between 0 and 10<br/>");
default:
switch (true) {
case myAge >= 80 || myAge <= 10:
document.write("myAge is 80 or above OR 10 or below<br/>");
default:
switch (true) {
case (myAge >= 30 || myAge <= 39) || (myAge >= 80 && myAge <= 89):
document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89");
}
}
}
}
Reasons:
- 由于您使用的是 if 系列,而不是 if-else-if,这意味着我们不应该在 Switch 中对 case 使用 break 语句
- 如果我们不使用 break,控制就会失效,因此不会检查连续 case 的条件
- 强制条件检查的唯一方法是在 default 关键字后使用嵌套的 Switch 语句!
关于javascript - 如何将 IF 转换为 JavaScript 中的 SWITCH 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49055179/