从input中取出的value字符串进行加减乘除操作时需要首先进行数值转换,比如:
var height = 20;
var addvalue = document.formname.addheight.value;
var newheight = height+addvalue;
如果在addheight中输入的值为13,则计算出来的newheight为2013,而我们期望的值为33,所以需要将字符串转化成数值,可以采用的方法是parseInt
上面的代码转换成如下内容就可以了:
var newheight = height+parseInt(addvalue);
如果带有小数的话,则需要采用方法parseFloat,否则小数将被忽略。
parseInt方法介绍摘抄如下:
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
- If the string begins with "0x", the radix is 16 (hexadecimal)
- If the string begins with "0", the radix is 8 (octal). This feature is deprecated
- If the string begins with any other value, the radix is 10 (decimal)
parseInt(string, radix)
- string Required. The string to be parsed
- radix Optional. A number (from 2 to 36) that represents the numeral system to be used