以下内容在一般情况下可能有用。
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 looks like 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.
出现问题的原因是来自表单的数据被视为字符串,因此+将连接而不是添加。
当从表单中读取应该是数值的数据时,您应该始终将其推入parseInt()或parseFloat(),这取决于您想要的是整数还是小数。
注意,这两个函数都没有真正地将字符串转换为数字。相反,它将从左到右解析字符串,直到它得到一个无效的数字字符或直到结尾,并转换已接受的内容。在parseFloat的情况下,它包括一个小数点,但不包括两个。
在有效数字之后的任何内容都将被忽略。如果字符串一开始不是数字,它们都会失败。然后你会得到NaN。
从表单中获取数字的一个好的通用技术是这样的:
var data=parseInt(form.elements['data'].value); // or parseFloat
如果你准备将一个无效字符串合并为0,你可以使用:
var data=parseInt(form.elements['data'].value) || 0;