Javascript 添加两个数字将它们连接起来而不是计算总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14496531/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:00:48  来源:igfitidea点击:

Adding two numbers concatenates them instead of calculating the sum

javascripthtml

提问by okconfused

I am adding two numbers, but I don't get a correct value.

我正在添加两个数字,但我没有得到正确的值。

For example, doing 1 + 2returns 12 and not 3

例如,执行1 + 2返回 12 而不是 3

What am I doing wrong in this code?

我在这段代码中做错了什么?

function myFunction() {
  var y = document.getElementById("txt1").value;
  var z = document.getElementById("txt2").value;
  var x = y + z;
  document.getElementById("demo").innerHTML = x;
}
<p>
  Click the button to calculate x.
  <button onclick="myFunction()">Try it</button>
</p>
<p>
  Enter first number:
  <input type="text" id="txt1" name="text1" value="1">
  Enter second number:
  <input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>

回答by elclanrs

They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +:

它们实际上是字符串,而不是数字。从字符串生成数字的最简单方法是在它前面加上+

var x = +y + +z;

回答by gerard

I just use Number():

我只是使用Number()

var i=2;  
var j=3;  
var k = Number(i) + Number(j); // 5  

回答by mitim

You need to use javaScript's parseInt()method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".

您需要使用 javaScript 的parseInt()方法将字符串转回数字。现在它们是字符串,所以添加两个字符串将它们连接起来,这就是为什么你得到“12”。

回答by Zorayr

Use parseInt(...)but make sure you specify a radix value; otherwise you will run into several bugs (if the string begins with "0", the radix is octal/8 etc.).

使用parseInt(...)但请确保指定一个基数值;否则你会遇到几个错误(如果字符串以“0”开头,基数是八进制/8等)。

var x = parseInt(stringValueX, 10);
var y = parseInt(stringValueY, 10);

alert(x + y);

Hope this helps!

希望这可以帮助!

回答by Vibhav Shreshth

Just add a simple type casting method as the input is taken in text. Use the following:

只需添加一个简单的类型转换方法,因为输入是在文本中进行的。使用以下内容:

    var y = parseInt(document.getElementById("txt1").value);
    var z = parseInt(document.getElementById("txt2").value);
    var x = y + z;

回答by Manngo

The following may be useful in general terms.

以下内容在一般情况下可能有用。

  • First, HTML form fields are limited to text. That applies especially to text boxes, even if you have taken pains to ensure that the value lookslike a number.

  • Second, JavaScript, for better or worse, has overloaded the +operator with two meanings: it adds numbers, and it concatenates strings. It has a preference for concatenation, so even an expression like 3+'4'will be treated as concatenation.

  • Third, JavaScript will attempt to change types dynamically if it can, and if it needs to. For example '2'*'3'will change both types to numbers, since you can't multiply strings. If one of them is incompatible, you will get NaN, Not a Number.

  • 首先,HTML 表单字段仅限于text。这尤其适用于文本框,即使您已经煞费苦心地确保该值看起来像一个数字。

  • 其次,无论好坏,JavaScript 都重载了+具有两种含义的运算符:添加数字和连接字符串。它偏好连接,所以即使是像这样的表达式3+'4'也会被视为连接。

  • 第三,如果可以,并且需要的话,JavaScript 将尝试动态更改类型。例如,'2'*'3'将两种类型都更改为数字,因为您不能将字符串相乘。如果其中之一不兼容,您将得到NaN, Not a Number。

Your problem occurs because the data coming from the form is regarded as a string, and the +will therefore concatenate rather than add.

出现您的问题是因为来自表单的数据被视为字符串,+因此将连接而不是添加。

When reading supposedly numeric data from a form, you should always push it through parseInt()or parseFloat(), depending on whether you want an integer or a decimal.

从表单中读取所谓的数字数据时,您应该始终将其推送到parseInt()parseFloat(),具体取决于您想要整数还是小数。

Note that neither function truly convertsa string to a number. Instead, it will parse the string from left to right until it gets to an invalid numeric character or to the end and convert what has been accepted. In the case of parseFloat, that includes one decimal point, but not two.

请注意,这两个函数都没有真正字符串转换为数字。相反,它会从左到右解析字符串,直到它得到一个无效的数字字符或最后,并转换已被接受的内容。在 的情况下parseFloat,这包括一位小数点,但不包括两位。

Anything after the valid number is simply ignored. They fail if the string doesn't even start off as a number. Then you will get NaN.

有效数字之后的任何内容都会被忽略。如果字符串甚至不是以数字开头,它们就会失败。然后你会得到NaN

A good general purpose technique for numbers from forms is something like this:

来自表单的数字的一个很好的通用技术是这样的:

var data=parseInt(form.elements['data'].value); //  or parseFloat

If you're prepared to coalesce an invalid string to 0, you can use:

如果您准备将无效字符串合并为 0,则可以使用:

var data=parseInt(form.elements['data'].value) || 0;

回答by Murtaza Khursheed Hussain

Simple

简单的

var result = parseInt("1") + parseInt("2");
console.log(result ); // Outputs 3

回答by Pushp Singh

This won't sum up the number; instead it will concatenate it:

这不会总结出数字;相反,它将连接它:

var x = y + z;

You need to do:

你需要做:

var x = (y)+(z);

You must use parseInt in order to specify the operation on numbers. Example:

您必须使用 parseInt 来指定对数字的操作。例子:

var x = parseInt(y) + parseInt(z); [final soulution, as everything us]

回答by taha

This code sums both the variables! Put it into your function

这段代码对两个变量求和!把它放到你的函数中

var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = (y +z);
document.getElementById("demo").innerHTML = x;`

回答by Asad Ali

If we have two input fields then get the values from input fields, and then add them using JavaScript.

如果我们有两个输入字段,则从输入字段中获取值,然后使用 JavaScript 添加它们。

$('input[name="yourname"]').keyup(function(event) {
    /* Act on the event */
    var value1 = $(this).val();
    var value2 = $('input[name="secondName"]').val();
    var roundofa = +value2+ +value1;

    $('input[name="total"]').val(addition);
});