I need assistance with changing a very long if/else if/else statement into a switch case statement. Conceptually im not certain of what should be put in the switch expression
if (!$jq('*').hasClass("answerPick")) {
// if nothing is selected
finalURL= "productResults.aspx?N=1320325";
}
else if (q1 === undefined && q2 === undefined && q3Multi === undefined) {
// if q1 a2 and q3 arent selected
finalURL= "productResults.aspx?N=1320325+" + q4Multi.join('+');
}
else if (q1 != undefined && q2 === undefined && q3Multi === undefined) {
// if q1 a2 and q3 arent selected
finalURL= "productResults.aspx?N=1320325+" q15 + q4Multi.join('+');
}
else if (q1 === undefined && q2 === undefined) {
// if q1 and q2 arent selected
finalURL= "productResults.aspx?N=1320325+" + q3Multi + q4Multi.join('+');
}
else if (q2 === undefined && q1 != undefined) {
// if only q2 is left unselected
finalURL = "productResults.aspx?N=" + q15 + q3Multi + q4Multi.join('+');
}
else if (q2 === undefined && q3Multi === undefined) {
// if only q1 is selected
finalURL = "productResults.aspx?N=" + q15;
}
else{
// if everything is selected
finalURL = "productResults.aspx?N=" + q2 + q3Multi + q4Multi.join('+');
}
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
Please let me know of anything else i should include. I think im missing something super obvious but conceptually it isnt clicking.
You can set a variable to a combination that indicates which variables are defined, and then switch on that.
if (!$jq('*').hasClass("answerPick")) {
// if nothing is selected
finalURL= "productResults.aspx?N=1320325";
} else {
var selected = (q1 === undefined ? "q1def" : "q1undef") + "+" + (q2 === undefined ? "q2def" : "q2undef") + "+" + (q3Multi === undefined ? "q3def" : "q3undef");
switch(selected) {
case "q1undef+q2undef+q3undef":
// if q1 a2 and q3 arent selected
finalURL= "productResults.aspx?N=1320325+" + q4Multi.join('+');
break;
case "q1def+q2undef+q3undef":
finalURL= "productResults.aspx?N=1320325+" q15 + q4Multi.join('+');
break;
case "q1undef+q2undef+q3def":
case "q1undef+q2undef+q3undef":
// if q1 and q2 arent selected
finalURL= "productResults.aspx?N=1320325+" + q3Multi + q4Multi.join('+');
break;
case "q1def+q2undef+q3def":
case "q1def+q2undef+q3undef":
// if only q2 is left unselected
finalURL = "productResults.aspx?N=" + q15 + q3Multi + q4Multi.join('+');
break;
case "q1def+q2undef+q3undef":
case "q1undef+q2undef+q3undef":
// if only q1 is selected
finalURL = "productResults.aspx?N=" + q15;
break;
default:
// if everything is selected
finalURL = "productResults.aspx?N=" + q2 + q3Multi + q4Multi.join('+');
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.