switch 表达式中可以使用数学运算符吗?

发布于 2024-12-13 07:39:23 字数 514 浏览 4 评论 0原文

我在 switch 表达式中使用数学运算符时遇到问题。

这就是我的代码当前的样子:

var x = 18;
var y = 82;

var result = x + y;

switch(result) {
case "200":
document.write("200!");
break;
case "500":
document.write("500!");
break;
case "100":
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}

解释:变量“result”的值为 100。我尝试将该值与 switch 运算符一起使用,但它不起作用。

我也尝试过使用方程本身作为开关表达式,但这也不起作用。

PS:我刚刚开始使用 JavaScript。我打赌我错过了一些明显的事情......

I'm having a problem using a mathematical operator in a switch expression.

This is what my code currently looks like:

var x = 18;
var y = 82;

var result = x + y;

switch(result) {
case "200":
document.write("200!");
break;
case "500":
document.write("500!");
break;
case "100":
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}

Explained: the variable "result" has a value of 100. I am trying to use that value with the switch operator, but it just isn't working.

I've also tried using the equation itself as the switch expression, but that doesn't work either.

P.S: I just started out with JavaScript. Bet I missed something obvious...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最舍不得你 2024-12-20 07:39:23

将“100”更改为 100 即可。 switch 必须使用 === 的语义,这意味着“类型和值相等”,而 == 会尝试使类型相似,然后进行比较。

编辑 - 这是显示它工作的屏幕截图

在此处输入图像描述

Change "100" to 100 and it works. switch must be using the semantics of === which means 'type and value are equal' vs ==, which will try to make the types similar and then compare.

EDIT -- here is a screenshot showing it working

enter image description here

秉烛思 2024-12-20 07:39:23

您将数字 100 与字符串 "100" 进行比较,两者不同。试试这个:

var x = 18;
var y = 82;

var result = x + y;

switch(result) {
case 200:
document.write("200!");
break;
case 500:
document.write("500!");
break;
case 100:
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}

You're comparing the number 100 to the string "100", that isn't the same. Try this:

var x = 18;
var y = 82;

var result = x + y;

switch(result) {
case 200:
document.write("200!");
break;
case 500:
document.write("500!");
break;
case 100:
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}
天煞孤星 2024-12-20 07:39:23

您在 case 语句中使用字符串。把引号 (") 去掉就可以了。

You are using strings in your case statements. Take the quotes (") out and you should be fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文