不久之前我需要一个复杂的开关帮助,但现在我用直接变量代替数组。我认为最好使用for语句,它不会显示结果。
对我来说这是一个辅助项目,所以如果您认为有任何方面可以改进,请告诉我。
<script>
var strMod=0;
var dexMod=0;
var conMod=0;
var intMod=0;
var wisMod=0;
var chaMod=0;
var strength = prompt("what is your strength?");
var dexterity = prompt("what is your dexterity?");
var constitution = prompt("what is your constitution?");
var intelligence = prompt("what is your intelligence?");
var wisdom = prompt("what is your wisdom?");
var charisma = prompt("what is your charisma?");
var abilities=[strength,dexterity,constitution,intelligence,wisdom,charisma];
var abiMod=[strMod,dexMod,conMod,intMod,wisMod,chaMod];
for (var i=0; i<abilities.length;i++){
switch(true){
case (abilities(i)>=0 && abilities(i)<2 && abilities(i)!==null):
abiMod(i)=-5;
break;
case (abilities(i)>=2 && abilities(i)<4):
abiMod(i)=-4;
break;
case (abilities(i)>=4 && abilities(i)<6):
abiMod(i)=-3;
break;
case (abilities(i)>=6 && abilities(i)<8):
abiMod(i)=-2;
break;
case (abilities(i)>=8 && abilities(i)<10):
abiMod(i)=-1;
break;
case (abilities(i)>=10 && abilities(i)<12):
abiMod(i)=0;
break;
case (abilities(i)>=12 && abilities(i)<14):
abiMod(i)=1;
break;
case (abilities(i)>=14 && abilities(i)<16):
abiMod(i)=2;
break;
case (abilities(i)>=16 && abilities(i)<18):
abiMod(i)=3;
break;
case (abilities(i)>=18 && abilities(i)<20):
abiMod(i)=4;
break;
case (abilities(i)>=20 && abilities(i)<22):
abiMod(i)=5;
break;
default:
abiMod(i)= prompt("what is your"+ abilities(i) +"modifier?");
break;
};
alert(abiMod(i));
};
</script>
答案 0 :(得分:1)
不是使用switch语句,而是在所有情况下都有一个共同的主题,因此可以使用数学公式。
以下是修订后的代码
for (var i = 0; i < abilities.length; i++) {
if (abilities[i] !== null && abilities[i] >= 0 && abilities[i] < 22) {
abiMod[i] = Math.floor(abilities[i] / 2) - 5;
}
else {
abiMod[i] = prompt("what is your "+ abilities[i] +" modifier?");
}
};
答案 1 :(得分:0)
对于初学者,您需要通过括号而不是parens来访问数组索引。
for (var i=0; i<abilities.length;i++){
switch(true){
case (abilities[i]>=0 && abilities[i]<2 && abilities[i]!==null):
abiMod[i]=-5;
break;
case (abilities[i]>=2 && abilities[i]<4):
abiMod[i]=-4;
break;
case (abilities[i]>=4 && abilities[i]<6):
abiMod[i]=-3;
break;
case (abilities[i]>=6 && abilities[i]<8):
abiMod[i]=-2;
break;
case (abilities[i]>=8 && abilities[i]<10):
abiMod[i]=-1;
break;
case (abilities[i]>=10 && abilities[i]<12):
abiMod[i]=0;
break;
case (abilities[i]>=12 && abilities[i]<14):
abiMod[i]=1;
break;
case (abilities[i]>=14 && abilities[i]<16):
abiMod[i]=2;
break;
case (abilities[i]>=16 && abilities[i]<18):
abiMod[i]=3;
break;
case (abilities[i]>=18 && abilities[i]<20):
abiMod[i]=4;
break;
case (abilities[i]>=20 && abilities[i]<22):
abiMod[i]=5;
break;
default:
abiMod[i]= prompt("what is your"+ abilities[i] +"modifier?");
break;
};
alert(abiMod[i]);
};
</script>