How to add several numbers in Javascript

3

Good as they are? I have a question on how I can make a value in javascrip can add it again and again, that is, for example I can make 1 + 1 + 1 equal to 3 without having to create a variable for each of them.

This is the calculator that I am doing and each button has a symbol now what I want to do is that it throws me a result

    
asked by maxwell salazar 09.08.2018 в 18:21
source

3 answers

1

You can write a string with the operation in a field and with the function eval evaluate the string and it will return the result

<!DOCTYPE html>
<html>
   <head>
    <script>
        var num = 0;
        function evaluar() {
            var ev = document.getElementById("evaluar").value
    
            document.getElementById("resultado").innerHTML = eval(ev);
        }
    </script>
    </head>
    <body >
         <input type="text" id="evaluar" value="1+1+1">
         <input name="suma" type="button" onClick="evaluar()" value="suma" />
         <p id="resultado"></p>        
    </body>
</html>
    
answered by 09.08.2018 в 18:48
-1

Implement a cycle for and increase the variable:

var i;
var numero = 1;
for (i = 0; i < 5; i++) {
    numero ++;
    console.log(numero)
}
    
answered by 09.08.2018 в 18:24
-1

Hello, use the eval function (text string). This will give you the result you want. Enter the entire operation string in the eval function.

eval("2 + 2");             // devuelve 4
    
answered by 09.08.2018 в 19:09