admin管理员组文章数量:1315775
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...
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...
Share Improve this question asked Oct 30, 2011 at 19:50 SweelySweely 3964 silver badges17 bronze badges3 Answers
Reset to default 5Change "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 pare.
EDIT -- here is a screenshot showing it working
You're paring 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..");
}
You are using strings in your case statements. Take the quotes ("
) out and you should be fine.
本文标签: javascriptCan a mathematical operator be used in a switch expressionStack Overflow
版权声明:本文标题:javascript - Can a mathematical operator be used in a switch expression? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741982825a2408499.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论