[英]How to add two values in javascript
This is a simple dropdown with values. 这是一个带有值的简单下拉列表。 I'm trying to pull the values as currency then add.
我试图将值作为货币拉出然后添加。
The values aren't being added ( 1+1=2
or 1+2=3
) but instead are concatenating ( 1+1=11
or 1+2=12
). 这些值没有被添加(
1+1=2
或1+2=3
),而是连接( 1+1=11
或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>
Use parseInt()
to cast your strings as integers. 使用
parseInt()
将字符串转换为整数。
var math= parseInt(x,10) + parseInt(y,10);
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt 请参阅https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt
To make sure your values are added as numbers, cast them to Number
first: 要确保将您的值添加为数字,请先将它们转换为
Number
:
Number('2') + Number('2') = 4
'2' + '2' = '22'
这些值被解释为字符串,您需要在添加它们之前使用parseInt将它们转换为int。
The substring()
function returns the substring of a given string, which is, of course, a string and not an object upon which math can be performed. substring()
函数返回给定字符串的子字符串,当然,这是一个字符串,而不是可以在其上执行数学运算的对象。 If you parse those strings into a number, using parseInt()
, then it will work: 如果使用
parseInt()
将这些字符串解析为数字,那么它将起作用:
var x= parseInt(strm.text.substr(t+1),10);
var y= parseInt(strb.text.substr(b+1),10);
Also, you don't need to keep redeclaring var
, you could instead comma-separated variable declarations: 此外,您不需要继续重新声明
var
,而是可以使用逗号分隔的变量声明:
var x = parseInt(strm.text.substr(t+1),10),
y = parseInt(strb.text.substr(b+1),10);
I discovered something interesting today. 我今天发现了一些有趣的事 I was doing the calculator project on theodinproject.
我在theodinproject上做了计算器项目。 I have addition, subtraction, multiplication, and division functions.
我有加法,减法,乘法和除法函数。 Subtraction, multiplication, and division works fine without needing to explicitly tell javascript to treat the parameter as a Number.
减法,乘法和除法工作正常,无需明确告诉javascript将参数视为数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.