switch statement to compare values greater or less than a number(用于比较大于或小于数字的值的 switch 语句)
问题描述
我想在我正在编写的一些简单代码中使用 switch
语句.
I want to use the switch
statement in some simple code i'm writing.
我正在尝试将括号中的变量与值进行比较 <13
或 >= 13
.
I'm trying to compare the variable in the parenthesis with values either < 13
or >= 13
.
这可以使用 Switch
吗?
var age = prompt("Enter you age");
switch (age) {
case <13:
alert("You must be 13 or older to play");
break;
case >=13:
alert("You are old enough to play");
break;
}
推荐答案
直接不可能,但间接你可以这样做
Directly it's not possible but indirectly you can do this
这样试试
switch (true) {
case (age < 13):
alert("You must be 13 or older to play");
break;
case (age >= 13):
alert("You are old enough to play");
break;
}
这里的 switch 总是会尝试找到真正的值.将首先返回 true 的情况将切换到该情况.
Here switch will always try to find true value. the case which will return first true it'll switch to that.
假设如果年龄小于 13 岁,这意味着该案例将为真,那么它将切换到该案例.
Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.
这篇关于用于比较大于或小于数字的值的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于比较大于或小于数字的值的 switch 语句


基础教程推荐
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01