将if-else-if语句转换为Javascript中的switch语句

问题描述 投票:-3回答:2

我无法将这段代码从if else语句转换为switch语句。该函数在html文档中调用。谁能给我一些指示?

function calcu(calcValue){

if (calcValue == '1')
{
  calc.output.value += '1';
}
else if (calcValue == '2')
{
  calc.output.value += '2';
}
else if (calcValue == '3')
{
  calc.output.value += '3';
}
javascript switch-statement
2个回答
0
投票

尝试

switch (calcValue ) {
  case '1':
  calc.output.value += '1';
    break;
   case '2':
  calc.output.value += '2';
    break;
  case '3':
  calc.output.value += '3';
    break;
  case '4':
  calc.output.value += '4';
    break;
  case '5':
  calc.output.value += '5';
    break;
}

0
投票

基本上可以将if转换为switch

if(something === match1){
    output = desirecOutput1;
}else if(something ==== match2){
    output = desiredOutput2;
}
....
....
....
else if(something === matchN){
    output = desiredOutputN;
}else{
    output = desiredOutputDefault;
}

至:

switch(something){
    case match1:
        output = desirecOutput1;
        break;
    case match2:
        output = desiredOutput2;
        break;
    ....
    ....
    case matchN:
        output = desiredOutputN;
        break;
    default:
        output = desiredOutputDefault;
        break;
}

基本上就是您的代码:

if (calcValue == '1')
{
  calc.output.value += '1';
}
else if (calcValue == '2')
{
  calc.output.value += '2';
}
else if (calcValue == '3')
{
  calc.output.value += '3';
}

它将是:

switch (calcValue) {
  case '1':
    calc.output.value += '1';
    break;
  case '2':
    calc.output.value += '2';
    break;
  case '3':
    calc.output.value += '3';
    break;
  default:
    calc.output.value += '0';
}
© www.soinside.com 2019 - 2024. All rights reserved.