简体   繁体   中英

Switch case addition in Javascript

I want to use this switch case, but it doesn't work:

switch(parseInt(num1),parseInt(num2),op)
    {
    case '+': resultat=(num1+num2);break;
    case '-': resultat=(num1-num2);break;
    case '*': resultat=(num1*num2);break;
    case '/': resultat=(num1/num2);break;
    case '<': resultat=(num1<num2);break;
    case '>': resultat=(num1>num2);break;
    case '%': resultat=(num1%num2);break;
    default:alert("Erreur: opérateur inconnu");
    }

num1 and num2 are collected before with a prompt command, they are numbers. They are converted from a chain to a number with the parseInt(). op is an operator like : *, /, +, -, % or >, <. It's collected befor with a prompt command as well. I just want to do an addition, like 3+5=8. Everything works exept for the addition...it return the answer 35. I don't understand why it don't see the addition even if I put it between ()...as you can see: case '+': resultat=(num1+num2);break;

Can someone can help me with that please?

It's becouse your num1 and num2 are strings - their sum is concatenated string. Also, parseInt returns parsed value, do not change variable value. Do this instead:

switch(op)
    {
    case '+': resultat=(parseInt(num1)+parseInt(num2));break;
    case '-': resultat=(parseInt(num1)-parseInt(num2));break;
    case '*': resultat=(parseInt(num1)*parseInt(num2));break;
    case '/': resultat=(parseInt(num1)/parseInt(num2));break;
    case '<': resultat=(parseInt(num1)<parseInt(num2));break;
    case '>': resultat=(parseInt(num1)>parseInt(num2));break;
    case '%': resultat=(parseInt(num1)%parseInt(num2));break;
    default:alert("Erreur: opérateur inconnu");
    }

You are only switching on the last item in the parenthesis, op . The parseInts are not doing anything. Therefore, your + block is still treating them as strings and concatenating.

num1 = parseInt(num1);
num2 = parseInt(num2);
switch(op)
    {
    case '+': resultat=(num1+num2);break;
    case '-': resultat=(num1-num2);break;
    case '*': resultat=(num1*num2);break;
    case '/': resultat=(num1/num2);break;
    case '<': resultat=(num1<num2);break;
    case '>': resultat=(num1>num2);break;
    case '%': resultat=(num1%num2);break;
    default:alert("Erreur: opérateur inconnu");
    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM