如何强制JS进行数学运算而不是将两个字符串放在一起

Sea*_*ean 98 javascript string math addition

我需要javascript将5添加到整数变量,但是它将变量视为字符串,因此它写出变量,然后在"字符串"的末尾添加5.我怎么能强迫它做数学呢?

var dots = document.getElementById("txt").value; // 5
function increase(){
    dots = dots + 5;
}
Run Code Online (Sandbox Code Playgroud)

输出: 55

我怎么强迫它输出10

可能是我的脚本中的错误吗?

我正在这样初始化55:

var dots = document.getElementById("txt").value; // 5
function increase(){
    dots = dots + 5;
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 105

你有这条线

dots = document.getElementById("txt").value;
Run Code Online (Sandbox Code Playgroud)

在您的文件中,这会将点设置为字符串,因为txt的内容不限于数字.

将它转换为int将行更改为:

dots = parseInt(document.getElementById("txt").value, 10);
Run Code Online (Sandbox Code Playgroud)

  • parseInt(...,10)也总是使用一个基数...一个健全性检查...如果(!dots || dots <1)也可以按顺序... (5认同)
  • shortcut ... dots = + document.getElementById("txt").value (3认同)

小智 50

最简单的:

dots = dots*1+5;
Run Code Online (Sandbox Code Playgroud)

点将转换为数字.

  • 比这更简单的是`dots = + dots + 5`. (29认同)

小智 20

不要忘记 - parseFloat();如果你处理小数,请使用.

  • 并且不要忘记float不是十进制数据类型http://stackoverflow.com/questions/588004/is-floating-point-math-broken (2认同)
  • 只需使用`Number`。 (2认同)

Ala*_* L. 8

parseInt() 应该做的伎俩

var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Run Code Online (Sandbox Code Playgroud)

给你

sum == 35
pin == "2510"
Run Code Online (Sandbox Code Playgroud)

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


Chr*_*vis 8

我要添加此答案,因为在这里看不到它。

一种方法是在值前放置一个“ +”字符

例:

var x = +'11.5' + +'3.5'
Run Code Online (Sandbox Code Playgroud)

x === 15

我发现这是最简单的方法

在这种情况下,该行:

dots = document.getElementById("txt").value;
Run Code Online (Sandbox Code Playgroud)

可以更改为

dots = +(document.getElementById("txt").value);
Run Code Online (Sandbox Code Playgroud)

强迫它成一个数字

注意:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
Run Code Online (Sandbox Code Playgroud)


小智 5

这也适合你:

dots -= -5;
Run Code Online (Sandbox Code Playgroud)


HSL*_*SLM 5

您可以在变量后面添加+,它将强制它为整数

var dots = 5
    function increase(){
        dots = +dots + 5;
    }
Run Code Online (Sandbox Code Playgroud)