最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can a mathematical operator be used in a switch expression? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 5

Change "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.

发布评论

评论列表(0)

  1. 暂无评论