如何强制JS进行数学运算而不是将两个字符串放在一起 [英] How to force JS to do math instead of putting two strings together
本文介绍了如何强制JS进行数学运算而不是将两个字符串放在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要javascript将5添加到整数变量,但是它将变量视为字符串,因此它写出变量,然后在字符串的末尾添加5。我怎么能强迫它做数学呢?
I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?
var dots = 5
function increase(){
dots = dots + 5;
}
输出: 55
如何强制输出 10
?
我的脚本可能是某个错误吗?
Could it possibly be an error in my script somewhere?
我正在初始化 dots
这样:
dots = document.getElementById("txt").value;
推荐答案
你有一行
dots = document.getElementById("txt").value;
在您的文件中,这会将点设置为字符串,因为txt的内容不限于一个数字。
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
将其转换为int将该行更改为:
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value);
这篇关于如何强制JS进行数学运算而不是将两个字符串放在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文