如何在javascript中添加两个值 [英] How to add two values in javascript
本文介绍了如何在javascript中添加两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个带有值的简单下拉列表。我试图将值拉为货币然后添加。
This is a simple dropdown with values. I'm trying to pull the values as currency then add.
未添加值( 1 + 1 = 2
或 1 + 2 = 3
)而是连接( 1 + 1 = 11
或 1 + 2 = 12
)。我在哪里错了?:
The values aren't being added (1+1=2
or 1+2=3
) but instead are concatenating (1+1=11
or 1+2=12
). Where am I going wrong here?:
<script>
function displayResult()
{
var strm=document.getElementById("matt").options[document.getElementById("matt").selectedIndex];
var t=strm.text.search("\\\$");
var strb=document.getElementById("box").options[document.getElementById("box").selectedIndex];
var b=strb.text.search("\\\$");
var x=strm.text.substr(t+1);
var y=strb.text.substr(b+1);
var math= x + y;
alert(strm.text.substr(t+1));
alert(strb.text.substr(b+1));
alert(math);
}
</script>
<form>
Select #1:
<select id="matt">
<option>$1.00</option>
<option>$2.00</option>
</select>
<br />
Select #2:
<select id="box">
<option>$3.00</option>
<option>$4.00</option>
</select>
</form>
<button type="button" onclick="displayResult()">Display index</button>
推荐答案
使用 parseInt()
将字符串转换为整数。
Use parseInt()
to cast your strings as integers.
var math= parseInt(x,10) + parseInt(y,10);
参见 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt
这篇关于如何在javascript中添加两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文