我想做这样的事情
switch (this.dealer) {
case 1-4:
// Do something.
break;
case 5-8:
// Do something.
break;
case 9-11:
// Do something.
break;
default:
break;
}正确的语法是什么?在JavaScript中是可能的吗?
所以this.dealer是一个整数,如果它在这些值之间,就做点什么。
发布于 2011-04-11 18:28:52
这是我想出来的另一种方式:
const x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}发布于 2013-10-10 07:44:53
在MarvinLabs回答的基础上递增,以使其更简洁:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}没有必要检查范围的下限,因为break语句将导致执行跳过剩余的情况,所以当执行到检查时,例如(x < 9),我们知道该值必须是5或更大。
当然,只有当案例保持原始顺序,并且我们假设整数值(如问题中所述)时,输出才是正确的-从技术上讲,范围在5到8.999999999999之间,因为js中的所有数字实际上都是双精度浮点数。
如果您希望能够移动case,或者发现在每个case语句中显示整个范围更具可读性,只需为每个case的较低范围添加一个小于或等于的检查即可:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x >= 5 && x < 9):
alert("between 5 and 8");
break;
case (x >= 9 && x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}请记住,这会增加额外的人为错误-有人可能试图更新范围,但忘记在两个地方更改它,留下了未覆盖的重叠或差距。例如,在这里,当我只编辑用于匹配8的大小写时,8的大小写将不会匹配任何内容。
case (x >= 5 && x < 8):
alert("between 5 and 7");
break;
case (x >= 9 && x < 12):
alert("between 9 and 11");
break;发布于 2011-04-11 18:17:30
switch(this.dealer) {
case 1:
case 2:
case 3:
case 4:
// Do something.
break;
case 5:
case 6:
case 7:
case 8:
// Do something.
break;
default:
break;
}如果您不喜欢连续的用例,那么只需使用if/else if/else语句。
https://stackoverflow.com/questions/5619832
复制相似问题