在javascript中没有正确添加2个数字 [英] Not adding 2 numbers correctly in javascript
本文介绍了在javascript中没有正确添加2个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 html 中有一个下拉列表,此处显示值,
i have a drop down list in my html with values show here,
<select id="thedropdown">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
还有我的 javascript:
And my javascript:
function myFunction()
{
var a = document.getElementById("thedropdown");
var b = a.options[a.selectedIndex].value;
var y=b;
var x=y+2;
var demoP=document.getElementById("demo")
demoP.innerHTML= x;
}
然而,当我点击按钮时,答案变成了 22,而它应该是 4.你可以看到我的问题.提前为帮助干杯
However the answer when i click the button makes it 22 when it should be 4. you can see my problem. Cheers for help in advance
推荐答案
现在您的代码连接字符串.你需要parseInt()
或 parseFloat()
(或 Number()
或 +
) 添加前的值.
Right now your code concatenates strings. You need to parseInt()
or parseFloat()
(or Number()
or +
) the values before adding.
使用 parseInt()
时,请确保 始终指定第二个参数(基数):
When using parseInt()
make sure to always specify the second argument (the radix):
b = parseInt(a.options[a.selectedIndex].value, 10);
这篇关于在javascript中没有正确添加2个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文