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

本文标签: javascriptCan a mathematical operator be used in a switch expressionStack Overflow