I recently started table top gaming and I don't want to deal with the calculations manually. Additionally, most of the apps have some kind of issue at any given time. I just began writing the basic javascript and can't seem to get the switch to work with the range. It reverts back to default. My code is below later on I will be putting the various modifiers/attributes into an array but I want the basic code to work first.
<script>
var strMod=0;
var strength = prompt("what is your strength?");
switch(strength){
case (strength>=0 && strength<2):
strMod=-5;
break;
case (strength>=2 && strength<4):
strMod=-4;
break;
case (strength>=4 && strength<6):
strMod=-3;
break;
case (strength>=6 && strength<8):
strMod=-2;
break;
case (strength>=8 && strength<10):
strMod=-1;
break;
case (strength>=10 && strength<12):
strMod=0;
break;
case (strength>=12 && strength<14):
strMod=1;
break;
case (strength>=14 && strength<16):
strMod=2;
break;
case (strength>=16 && strength<18):
strMod=3;
break;
case (strength>=18 && strength<20):
strMod=4;
break;
case (strength>=20 && strength<22):
strMod=5;
break;
default:
strMod= prompt("what is your strength modifier?");
break;
}
console.log(strMod);
</script>
答案 0 :(得分:4)
Change switch(strength)
to switch(true)
. This should work since you are comparing the results of the case statements to the value true
, not to the value of strength
.
JSFiddle: https://jsfiddle.net/eusw15g9/
See this accepted answer for more info: Expression inside switch case statement
答案 1 :(得分:1)
Do you really need to use switch-case
? Why don't you just do something like this:
var strength = prompt("What is your strength?");
var strMod = Math.floor(strength / 2) -5;
document.getElementById("foo").innerHTML = strMod;
<div id="foo"></div>
答案 2 :(得分:1)
A switch does not work like that -- what you pass to switch
is compared via equality to all of the case values. If there is a match, the case is selected otherwise the default
happens (if one is defined).
You can either switch to a long if () {} else if () {} ... else {}
chain or write a function that converts the range to a numerical value and switch on that value.
The function isn't even necessary in your case:
switch(Math.ceil(strength/2)){
case 1:
strMod=-5;
break;
case 2:
strMod=-4;
break;
case 3:
strMod=-3;
break;
case 4:
strMod=-2;
break;
...
And then simply guard for <= 0
or >= MAX
with an if
before the switch.
答案 3 :(得分:0)
A switch statement evaluates expressions using strict comparison ===
. This means that the input expression will be === compare with first case clause matching in your switch. Therefore in your example above it will turn out to be default
statement