gpt4 book ai didi

使用 Switch 语句的 JavaScript - 未获得预期输出

转载 作者:行者123 更新时间:2023-11-28 13:29:31 24 4
gpt4 key购买 nike

我对此很陌生,还有很多东西要学习。我在这段 JavaScript 中使用了 Switch 语句,但没有得到 document.write 行的预期输出。如有任何帮助、意见和建议,我们将不胜感激。 - 谢谢!

            <script type="text/javascript">

var myAge = Number(prompt("Enter your age", 30));
myAge = parseInt(myAge);

switch (myAge)
{
case (myAge >= 0 && myAge <= 10):
document.write("myAge is between 0 and 10");
break;

case (!(myAge >= 0 && myAge <=10)):
document.write ("myAge is NOT between 0 and 10 <br />");
break;

case (myAge >= 80 || myAge <= 10):
document.write ("myAge is 80 or above OR 10 or below <br />");
break;

case (myAge >= 30 && myAge <=39 || (myAge >= 80 && myAge <= 89)):
document.write("myAge is between 30 and 39 or myAge is between 80 and 89");
break;

default:
document.write("You did not enter a number. Please enter a number.");
break;
}

document.write("<BR>Execution continues here");


</script>

这是我仅使用“if”编写的内容。

        <script type="text/javascript">

var myAge = Number(prompt("Enter your age", 30));

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");
}


</script>

这是我必须引用的使用“switch”的示例代码。

<script type="text/javascript">

var secretNumber = prompt("Pick a number between 1 and 5:", "");
secretNumber = parseInt(secretNumber);

switch (secretNumber)
{
case 1:
document.write("Too low!");
break;

case 2:
document.write("Too low!");
break;

case 3:
document.write("You guessed the secret number!");
break;

case 4:
document.write("Too high!");
break;

case 5:
document.write("Too high!");
break;

default:
document.write("You did not enter a number between 1 and 5.");
break;
}
document.write("<BR>Execution continues here");

</script>

最佳答案

您需要重新考虑 case 表达式中的逻辑。

让我在您的代码中进行替换,以说明错误

var test = myAge >= 0 && myAge <= 10;
if (test) {
...
} else if (!test) {
...
} else {
// WILL NEVER BE RUN
}

如果您想使用 switch 语句,您必须了解您正在使用的数据背后的类型。

true : Boolean
false : Boolean
9 : Number
1.0 : Number

在下面的示例中,v 必须与 value1value2 具有相同的类型。

switch(v)
{
case (value1):
...
case (value2):
...
}

问题是以下类型与您的示例不匹配。

v = Number
value1 = Boolean
value2 = Boolean

关于使用 Switch 语句的 JavaScript - 未获得预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26207772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com