Take the value of the operator to perform javascript operations

2

I am starting to learn javascript and the fact is that we are doing a calculator and I do not know how to do it so that I do not concatenate the two numbers that I have to add: (when adding 12 and 20 in the alert I get 12 + 20 , that is, the + symbol does not take it as such)

I attached the code:

function cal() {
var numero1 = document.forms["form1"]["num1"].value;
var numero2 = document.forms["form1"]["num2"].value;
var operador = document.forms["form1"]["operador"].value;
num1 = parseInt(numero1);    
num2 = parseInt(numero2);

 if( Number.isInteger(num1) && Number.isInteger(num2)){
alert("Hola, has metido dos numeros"+operador);
if(operador == "+" || operador == "-" || operador == "*" || operador == "/")
   {
   alert("El operador esta bien ahora vamos a ver el resultado de la operación");
       var resultado = "";
       resultado = num1+operador.valueOf+num2 ;
       alert(resultado);
   }     

 }
    else{
        alert("Algo falla, comprueba si lo que has metido son números de verdad");

    }

}
    
asked by Mariopenguin 02.11.2017 в 20:20
source

2 answers

2

The problem is here

var resultado = '';

Your variable is being initialized as a string, so + is now concatenation instead of sum. Change the line to:

var resultado = 0;

And you will get the result you expect

    
answered by 02.11.2017 в 20:25
2

You must convert the values to add to numbers, in fact at the moment you do the first condition you are doing it, then you should do it again in the sum:

resultado = (Number(num1) + operador.valueOf + Number(num2));
alert(resultado);

With that I should give you.

    
answered by 02.11.2017 в 20:36