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)
小智 50
最简单的:
dots = dots*1+5;
Run Code Online (Sandbox Code Playgroud)
点将转换为数字.
小智 20
不要忘记 - parseFloat();
如果你处理小数,请使用.
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
我要添加此答案,因为在这里看不到它。
一种方法是在值前放置一个“ +”字符
例:
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)
您可以在变量后面添加+,它将强制它为整数
var dots = 5
function increase(){
dots = +dots + 5;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
115673 次 |
最近记录: |