如何强制 JS 做数学运算而不是将两个字符串放在一起 [英] How to force JS to do math instead of putting two strings together
问题描述
我需要 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 = document.getElementById("txt").value; // 5
function increase(){
dots = dots + 5;
}
输出:55
如何强制它输出10
?
推荐答案
你有线路
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, 10);
注意:这里的 10
指定十进制(基数为 10).如果没有这个,一些浏览器可能无法正确解释字符串.请参阅 MDN:parseInt
.
Note: The 10
here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt
.
这篇关于如何强制 JS 做数学运算而不是将两个字符串放在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!