问题描述
我是JavaScript的新手.这是我的剧本
i am a a newbie in javascript.here is my script
var marks=11;
switch(marks){
case (marks<20):
console.log('Yes Freaking Failed');
break;
case (marks>20):
console.log('Ahh Its Ok');
break;
case (marks>80):
console.log('Whooping');
break;
default:
console.log('Cant say u maybe Flunked');
break;
}
现在我认为它应该显示Yes Freaking Failed
,因为标记少于20.但是它显示了can't say..
为什么?请告诉我我在哪里做错了.谢谢.
Now i think it should display Yes Freaking Failed
because the marks are less than 20. But it shows can't say..
why is that?Please tell me where i am doing it wrong.thanks.
推荐答案
撰写时
switch (x) {
case(y):
...
}
相当于测试
if (x == y) {
...
}
所以
case (marks < 20):
表示:
if (marks == (marks < 20)) {
您不能将case
用于此类范围测试,需要使用一系列if/else if
:
You can't use case
for range tests like this, you need to use a series of if/else if
:
if (marks < 20) {
console.log('Yes Freaking Failed');
} else if (marks < 80) {
console.log('Ahh Its OK');
} else {
console.log('Whooping');
}
还要注意,如果它按照您的想法工作,它将永远不会执行marks > 80
,因为它也将匹配marks > 20
,并且始终执行第一个匹配的大小写.
Also notice that if it worked the way you thought, it could never execute marks > 80
, because that would also match marks > 20
, and the first matching case is always executed.
不需要Cant say u maybe flunked
情况,因为没有其他可能性.
There's no need for the Cant say u maybe flunked
case, because there are no other possibilities.
这篇关于开关盒未显示正确结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!