Javascript nested switch statement inside if else statement
Need some help with the following javascript problem that won't resolve. I'm a novice and doing my best to find a good solution so I can complete my thesis research. The code is designed to run inside an online survey program called Qualtrics. Each var represents pipped data from question responses. I have tested these and they work fine.
One of the switch works fine outside the if-else statement. However, when combined, things don't work.
Any help much appreciated.
var storeLow = ${q://QID83/ChoiceGroup/SelectedChoices};
var storeHigh = ${q://QID82/ChoiceGroup/SelectedChoices};
var cash = 0;
if(storeLow >= 1)
{
switch(storeLow) {
case 5:
cash = 200;
break;
case 3:
case 6:
case 11:
case 12:
cash = 150;
break;
case 1:
case 2:
case 4:
case 7:
case 8:
case 9:
case 10:
case 13:
case 14:
case 15:
case 16:
cash = 100;
break;
default:
cash = 50;
break;
}
} else {
switch(stor开发者_如何学GoeHigh) {
case 3:
cash = 200;
break;
case 6:
case 10:
case 11:
case 15:
cash = 150;
break;
case 1:
case 2:
case 4:
case 5:
case 7:
case 8:
case 9:
case 12:
case 13:
case 14:
case 16:
cash = 100;
break;
default:
cash = 50;
break;
}
}
I'm going to take a wild guess here and believe that maybe one of your variables is actually carrying string values instead of integers. Try substituting:
switch(storeLow) {
...
switch(storeHigh) {
with
switch( parseInt(storeLow, 10) ) {
...
switch( parseInt(storeHigh, 10) ) {
A better approach will be using a javascript object to assign Cash ranges, instead of using ugly code with so many switch cases:
eg.
var myCashCriteria = { '15': 100 , '16' : 100, '17' : 100,'5' : 200 }
var myCash = getCash(16);
function getCash(num)
{
var numKey = num + ''; // convert num to string
if(myCashCriteria[numKey])
return myCashCriteria[numKey];
else
return 0 ; // default value
}
精彩评论