javascript:在 switch case 中使用条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5464362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript: using a condition in switch case
提问by haemse
Sorry for that dumb question.
How can I use a condition for a case in the javascript switch-case language element?
Like in the example below, a case should match when the variable liCount
is <=5 and >0; however, my code does not work:
对不起,这个愚蠢的问题。如何在 javascript switch-case 语言元素中为 case 使用条件?如下例所示,当变量liCount
<=5 且 >0时,大小写应该匹配;但是,我的代码不起作用:
switch (liCount) {
case 0:
setLayoutState('start');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case (liCount<=5 && liCount>0):
setLayoutState('upload1Row');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case (liCount<=10 && liCount>5):
setLayoutState('upload2Rows');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case (liCount>10):
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
}
Thanks for any advice!
感谢您的任何建议!
回答by dmp
This works:
这有效:
switch (true) {
case liCount == 0:
setLayoutState('start');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=5 && liCount>0:
setLayoutState('upload1Row');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=10 && liCount>5:
setLayoutState('upload2Rows');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount>10:
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
}
A previous version of this answer considered the parentheses to be the culprit. In truth, the parentheses are irrelevant here - the only thing necessary is switch(true){...}
and for your case expressions to evaluate to booleans.
此答案的先前版本认为括号是罪魁祸首。事实上,括号在这里无关紧要 - 唯一需要的是switch(true){...}
并且让您的 case 表达式评估为布尔值。
It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..}
and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.
之所以有效,是因为我们给 switch 的值被用作比较的基础。因此,case 表达式,也计算为布尔值将确定运行哪个 case。也可以扭转这一switch(false){..}
局面,并通过并让所需的表达式评估为 false 而不是 true ......但个人更喜欢处理评估为真的条件。但是,它也确实有效,因此值得牢记以了解它在做什么。
Eg: if liCount is 3, the first comparison is true === (liCount == 0)
, meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0)
. This expression evaluates to true, meaning this case is run, and terminates at the break
. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.
例如:如果 liCount 为 3,则第一次比较为true === (liCount == 0)
,这意味着第一种情况为假。然后切换到下一个案例true === (liCount<=5 && liCount>0)
。此表达式的计算结果为 true,这意味着此案例已运行,并在 处终止break
。我在此处添加了括号以使其更清晰,但它们是可选的,具体取决于表达式的复杂性。
It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ...
might introduce a lot of visual noise or fragility.
它非常简单,而且是处理一系列条件的一种巧妙方法(如果它适合您尝试做的事情),其中可能ìf() ... else if() ... else if () ...
会引入大量视觉噪音或脆弱性。
Use with caution, because it is a non-standard pattern, despite being valid code.
谨慎使用,因为它是一种非标准模式,尽管它是有效的代码。
回答by Eric
You've wayovercomplicated that. Write it with if statements instead like this:
你已经把事情复杂化了。用 if 语句来写它,而不是这样:
if(liCount == 0)
setLayoutState('start');
else if(liCount<=5)
setLayoutState('upload1Row');
else if(liCount<=10)
setLayoutState('upload2Rows');
$('#UploadList').data('jsp').reinitialise();
Or, if ChaosPandionis trying to optimize as much as possible:
或者,如果ChaosPandion试图尽可能地优化:
setLayoutState(liCount == 0 ? 'start' :
liCount <= 5 ? 'upload1Row' :
liCount <= 10 ? 'upload2Rows' :
null);
$('#UploadList').data('jsp').reinitialise();
回答by ChaosPandion
You want to use if statements:
您想使用 if 语句:
if (liCount === 0) {
setLayoutState('start');
} else if (liCount <= 5) {
setLayoutState('upload1Row');
} else if (liCount <= 10) {
setLayoutState('upload2Rows');
}
$('#UploadList').data('jsp').reinitialise();
回答by Mark Kahn
See dmp's answerbelow. I'd delete this answer if I could, but it was accepted so this is the next best thing :)
请参阅下面dmp 的回答。如果可以的话,我会删除这个答案,但它被接受了,所以这是下一个最好的事情:)
You can't. JS Interpreters require you to compare against the switch statement (e.g. there is no "case when" statement). If you really want to do this, you can just make if(){ .. } else if(){ .. }
blocks.
你不能。JS 解释器要求您与 switch 语句进行比较(例如,没有“case when”语句)。如果你真的想这样做,你可以制作if(){ .. } else if(){ .. }
块。
回答by Mike Samuel
switch (true) {
case condition0:
...
break;
case condition1:
...
break;
}
will work in JavaScript as long as your conditions return proper boolean
values, but it doesn't have many advantages over else if
statements.
只要您的条件返回正确的boolean
值,它就可以在 JavaScript 中工作,但与else if
语句相比,它没有太多优势。
回答by Naftali aka Neal
If that's what you want to do, it would be better to use if
statements. For example:
如果这就是您想要做的,最好使用if
语句。例如:
if(liCount == 0){
setLayoutState('start');
}
if(liCount<=5 && liCount>0){
setLayoutState('upload1Row');
}
if(liCount<=10 && liCount>5){
setLayoutState('upload2Rows');
}
var api = $('#UploadList').data('jsp');
api.reinitialise();
回答by ThiefMaster
That's a case where you should use if
clauses.
在这种情况下,您应该使用if
子句。
回答by Ender
Your code does not work because it is not doing what you are expecting it to do. Switch blocks take in a value, and compare each case to the given value, looking for equality. Your comparison value is an integer, but most of your case expressions resolve to a boolean value.
您的代码不起作用,因为它没有做您期望它做的事情。Switch 块接收一个值,并将每种情况与给定值进行比较,寻找相等性。您的比较值是一个整数,但大多数 case 表达式解析为布尔值。
So, for example, say liCount = 2
. Your first case will not match, because 2 != 0
. Your second case, (liCount<=5 && liCount>0)
evaluates to true
, but 2 != true
, so this case will not match either.
因此,例如,说liCount = 2
。您的第一个案例将不匹配,因为2 != 0
. 您的第二种情况(liCount<=5 && liCount>0)
评估为true
, but 2 != true
,因此这种情况也不匹配。
For this reason, as many others have said, you should use a series of if...then...else if
blocks to do this.
因此,正如许多其他人所说,您应该使用一系列if...then...else if
块来执行此操作。
回答by kennebec
if the possible values are integers you can bunch up cases. Otherwise, use ifs.
如果可能的值是整数,您可以将案例组合在一起。否则,请使用 ifs。
var api, tem;
switch(liCount){
case 0:
tem= 'start';
break;
case 1: case 2: case 3: case 4: case 5:
tem= 'upload1Row';
break;
case 6: case 7: case 8: case 9: case 10:
tem= 'upload2Rows';
break;
default:
break;
}
if(tem) setLayoutState((tem);
api= $('#UploadList').data('jsp');
api.reinitialise();
回答by Harshit Pant
Notice that we don't pass score to the switch but true. The value we give to the switch is used as the basis to compare against.
请注意,我们没有将 score 传递给 switch 而是 true。我们给开关的值用作比较的基础。
The below example shows how we can add conditions in the case: without any if statements.
下面的例子展示了我们如何在 case 中添加条件:没有任何 if 语句。
function getGrade(score) {
let grade;
// Write your code here
switch(true) {
case score >= 0 && score <= 5:
grade = 'F';
break;
case score > 5 && score <= 10:
grade = 'E';
break;
case score > 10 && score <= 15:
grade = 'D';
break;
case score > 15 && score <= 20:
grade = 'C';
break;
case score > 20 && score <= 25:
grade = 'B';
break;
case score > 25 && score <= 30:
grade = 'A';
break;
}
return grade;
}