难以概念化我如何将if if语句更改为switch语句

问题描述 投票:0回答:1

我需要将非常长的if / else if / else语句更改为switch case语句的帮助。从概念上来说,我不确定应该在switch表达式中放置什么]

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
} 

[请让我知道我应包括的其他内容。我认为我缺少一些非常明显的东西,但从概念上讲它并不是单击。

javascript if-statement switch-statement
1个回答
0
投票
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+q3Multiundef": finalURL= "productResults.aspx?N=1320325+" q15 + q4Multi.join('+'); break; case "q1undef+q2undef": // if q1 and q2 arent selected finalURL= "productResults.aspx?N=1320325+" + q3Multi + q4Multi.join('+'); break; case "q2undef+q1def": // if only q2 is left unselected finalURL = "productResults.aspx?N=" + q15 + q3Multi + q4Multi.join('+'); break; case "q2undef+q3Multiundef": // 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; } }
© www.soinside.com 2019 - 2024. All rights reserved.