添加 Javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8527237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Javascript variables
提问by codedude
So, I'm relatively new to JavaScript and I was wondering how I would add the values from two inputs and echo out the result. Here's what I have so far:
所以,我对 JavaScript 比较陌生,我想知道如何将两个输入的值相加并输出结果。这是我到目前为止所拥有的:
function math (form) {
var input1 = form.input1.value;
var input2 = form.input2.value;
var input3 = input1 + input2;
document.write (input3);
}
<form action="" method="GET">
<input type="text" name="input1">
<input type="text" name="input2">
<input type="button" name="button" onClick="math(this.form)">
</form>
I expected that when I entered a number into each input it would spit out the sum of the two numbers. Instead it just prints both numbers individually.
我预计当我在每个输入中输入一个数字时,它会吐出两个数字的总和。相反,它只是单独打印两个数字。
How can I get it to print the sum of the two numbers?
我怎样才能让它打印两个数字的总和?
回答by pimvdb
.valuegives the characters in the textbox, i.e. a string. You somehow need to tell JavaScript that it's a number. Otherwise you're concatenating the strings (str + stris concatenating; num + numis adding arithmetically).
.value给出文本框中的字符,即字符串。你需要告诉 JavaScript 它是一个数字。否则,您将连接字符串(str + str正在连接;num + num在算术上相加)。
String to number conversion is most easily done with +like this:
字符串到数字的转换最容易完成,+如下所示:
+input1
So in your case:
所以在你的情况下:
document.write(+input1 + +input2);
However, document.writeis not the way to display things. You probably want alert, or put it in another textbox or something like that. document.writewill clear the screen.
然而,document.write并不是展示事物的方式。你可能想要alert,或者把它放在另一个文本框或类似的东西中。document.write将清除屏幕。
回答by Andrew
They are strings when you read them in, they must be parsed first,
当你读入它们时它们是字符串,它们必须首先被解析,
var input3 = parseInt(input1, 10) + parseInt(input2, 10);
[Edit]Just to elaborate, the difference between parseIntand the Unary Plus is in the error handling,
[编辑]详细说明一下,parseInt和一元加的区别在于错误处理,
var a = parseInt('123o45', 10); //123
var b = +'123o45' // NaN
回答by Damen TheSifter
parseInt is your firend here..
parseInt 是你的朋友。
function math (form) {
var input1 = form.input1.value;
var input2 = form.input2.value;
var input3 = parseInt(input1, 10) + parseInt(input2, 10);
document.write (input3);
}
回答by Christofer Eliasson
You would have to parse them to integers first using parseInt.
您必须首先使用 parseInt 将它们解析为整数。
回答by Zack
Mine worked well with parsing them to Floatas I am having decimal digits. Instead of parseInt(), I used parseFloat().
我的解析它们的效果很好,Float因为我有十进制数字。相反parseInt(),我使用了parseFloat().
I hope it'll help somebody in future.
我希望它会在未来帮助某人。

