Cómo forzar a JS a hacer matemáticas en lugar de poner dos cuerdas juntas


Necesito javascript para agregar 5 a una variable entera, pero en su lugar trata la variable como una cadena, por lo que escribe la variable, luego agrega 5 al final de la "cadena". ¿Cómo puedo forzarlo a hacer matemáticas en su lugar?

var dots = 5
function increase(){
    dots = dots + 5;
}

Salidas: 55

¿Cómo puedo forzarlo a salir 10?

¿Podría ser un error en mi script en algún lugar?

Estoy inicializando dots así:

dots = document.getElementById("txt").value;
Author: ibrahim mahrir, 2011-01-30

7 answers

Tienes la línea

dots = document.getElementById("txt").value;

En su archivo, esto establecerá que los puntos sean una cadena porque el contenido de txt no está restringido a un número.

Para convertirlo en un int cambie la línea a:

dots = parseInt(document.getElementById("txt").value);
 100
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-30 05:53:24

El más simple:

dots = dots*1+5;

Los puntos se convertirán en número.

 48
Author: mier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-06 13:44:55

NO SE OLVIDE - Use parseFloat(); si está tratando con decimales.

 16
Author: Nicolas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 05:55:07

parseInt() debería hacer el truco

var number = "25";
var sum = parseInt(number) + 10;
var pin = number + 10;

Te da

sum == 35
pin == "2510"

Http://www.w3schools.com/jsref/jsref_parseint.asp

 6
Author: Alan L.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-13 20:22:27

Esto también funciona para ti:

dots -= -5;
 3
Author: Holger.Buick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-28 07:51:51

Estoy agregando esta respuesta porque no la veo aquí.

Una forma es poner un carácter ' + ' delante del valor

Ejemplo:

var x = +'11.5' + +'3.5'

X = = = 15

He encontrado que esta es la manera más simple

En este caso, la línea:

dots = document.getElementById("txt").value;

Podría cambiarse a

dots = +(document.getElementById("txt").value);

Para forzarlo a un número

NOTA:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
 3
Author: Christopher Strolia-Davis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-17 12:35:26

ACTUALIZADO desde la última votación en contra....

Solo vi la porción

var dots = 5
function increase(){
    dots = dots+5;
}

Antes, pero más tarde se me mostró que el cuadro txt alimenta la variable dots. Debido a esto, usted tendrá que estar seguro de "limpiar" la entrada, para asegurarse de que solo tiene números enteros, y no código malicioso.

Una manera fácil de hacer esto es analizar el cuadro de texto con un evento onkeyup() para asegurarse de que tiene caracteres numéricos:

<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>

Donde el evento daría un error y borraría el último carácter si el valor no es un número:

<script type="text/javascript">
    function GetChar (event){
        var keyCode = ('which' in event) ? event.which : event.keyCode;
        var yourChar = String.fromCharCode();
        if (yourChar != "0" &&
            yourChar != "1" &&
            yourChar != "2" &&
            yourChar != "3" && 
            yourChar != "4" &&
            yourChar != "5" &&
            yourChar != "6" && 
            yourChar != "7" &&
            yourChar != "8" && 
            yourChar != "9")
        {
            alert ('The character was not a number');
            var source = event.target || event.srcElement;
            source.value = source.value.substring(0,source.value-2);
        }
    }
</script>

Obviamente podrías hacer eso con regex, también, pero tomé la salida perezosa.

Desde entonces sabrías que solo los números podrían estar en la caja, deberías poder usar eval():

dots = eval(dots) + 5;
 -3
Author: vapcguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-11 18:39:59